My goal is to have a background image for the body with content placed on top of it. I am using CSS to set the background image through the body selector with the ::before pseudo-element. However, the image does not show up in the background without setting z-index: -1. This approach allows me to fix the image to the viewport without affecting scrolling behavior on the page.
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>
It raises the question: Why is z-index: -1 needed for the image to be visible in the background? Shouldn't the ::before pseudo-element place it automatically behind all content as intended?