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;
}
CodePudding user response:
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>
CodePudding user response:
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>
CodePudding user response:
Using the :before or :after CSS pseudo-elements, you apply the div with a background image and set an opacity on it.