I am trying to set the background of the body to an image using background-image
, and I have content that I want to be placed on top of the image. In the CSS, I am setting the background using the body
selector with the ::before
pseudo-element; however, the image doesn't come in the background unless if I use z-index: -1
. (I am using ::before
because I want to fix the image to the viewport, and I don't want to do that in the regular body
selector as that will fix all the content on the page and prevent me from scrolling through the content.)
body::before {
content: "";
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
background-image: url(...);
}
form {
background: purple;
border-radius: 5px;
padding: 50px;
width: 40%;
margin: 0 auto;
}
<html>
<body>
<form></form>
</body>
</html>
My question is: Why do I need to set the z-index to -1 in order for the image to appear in the background? Why doesn't it appear in the background automatically "before" all the content? Isn't that what the purpose of ::before
is?