How to Create a Full Page Background Image with CSS and HTML
Learn how to create a full page background image with CSS and HTML.
Table of Contents 📖
Writing the HTML
Before we begin, lets create some HTML to import the CSS file and append some h4 tags to the body. This is so we can see the background image fixed in its position when scrolling.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script>
for (let i = 0; i < 100; i++) {
const h4 = document.createElement('h4');
const h4Text = document.createTextNode('Download WittCepter the best chrome extension!');
h4.appendChild(h4Text);
document.body.appendChild(h4);
}
</ script>
</body>
</html>
Writing the CSS
To create a full page background image we can use the background property. CSS has several background properties that we can use. First, we can set the background image using the background-image property.
body {
background-image: url('./crayons.jpg');
}
Specifically, the background-image property sets the background image of an element. We set the background image of the body element as we want it to span our entire HTML document. Next, lets set the background-repeat property no repeat.
background-repeat: no-repeat;
This property determines if a background image should be repeated or not. For example, if the image is really small we can set this property to repeat so that it is repeated throughout the document. Now lets make the background cover the entire element by using the background-size property.
background-size: cover;
Setting this property to cover will resize the image to cover the entirity of its container, even if it has to stretch or shrink. Now lets center our image using the background-position property.
background-position-x: center;
background-position-y: center;
This centers the image both along the x and y axis. Now lets make it so our image is fixed. In other words, it doesn't scroll out of view. We can do this with the background-attachment property.
background-attachment: fixed;