0

I have created an ID for my HTML body called #indexbody. I put a background image with CSS using background-image:url("hs2.webp");. Because I Have done it this way, is there a way to change the background opacity of my image without dimming the entire body?

CSS:

#indexbody{
  background-image:url("hs2.webp");
  background-size: 100% auto;
}

3 Answers3

1

If you put the background-image on the before pseudo image rather than the actual body element you can set its opacity down without that affecting the whole body element.

Here's a simple snippet:

body {
  width: 100vw;
  min-height: 100vh;
  margin: 0;
}

body::before {
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url(https://picsum.photos/id/1015/300/300);
  background-size: cover;
  opacity: 0.4;
  position: absolute;
}
<body></body>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
0

There are many different ways to do this. One of the most common is using a pseudo-element. In this case, I used :after to create the background color overtop of the picture then used z-index to make sure my absolutely positioned text elements are layered ahead of the pseudo-element.

#indexbody {
  background-image: url("https://dummyimage.com/600x400/000/fff");
  /* background-color: rgba(0, 0, 0, .5); --> solution without using psuedo-element */
  background-size: cover;
  background-position: center;
  width: 100%;
  height: 500px;
  position: relative;
}

#indexbody:after {
  content: "";
  position: absolute;
  background-color: orange;
  opacity: .5;
  inset: 0;
}

p {
  position: absolute;
  color: white;
  background-color: blue;
  z-index: 1;
  text-align: center;
}
<div id="indexbody">
  <p>absolutely positioned element overtop, unaffected by opacity</p>
</div>
Kameron
  • 10,240
  • 4
  • 13
  • 26
0

Using the :before or :after CSS pseudo-elements, you apply the div with a background image and set an opacity on it.

alanfljesus
  • 117
  • 2
  • 9
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 30 '22 at 14:48