1

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?

Huangism
  • 16,278
  • 7
  • 48
  • 74
hsivru
  • 55
  • 1
  • 8

1 Answers1

1

A bit tricky part here. First ::before doesn't mean that this pseudo element goes precisely before form element. In fact this means create pseudo element before any children of form element. Vice versa for ::after. Second you set position: fixed; for ::before thats create new stacking context for it - simple this is the reason (not really check: Why does position:relative; appear to change the z-index?) why it overlaps the content of form element.

UPD Probably you should use background-attachment: fixed; on body element https://www.w3schools.com/cssref/pr_background-attachment.asp

ishaba
  • 551
  • 2
  • 10