Archived topic
How to change opacity of background image in header element
5 replies · Started by mkjj on April 10, 2023
I'm ususally not a big fan of text on a fancy background image. It's hard to get it right on mobile devices. Unfortunately, my customer wants it on this site. On small devices I have to change the opacity of the background to keep the text readable. As far as I know, you can't change the opacity of a background image using CSS. As a workaround I use a media query that loads a modified image for mobile devices. It's working, but not very elegant. Would you have a better solution for this? Or would you conside this an acceptable solution?
HTML in the hero section is pretty simple:
<div class="hero">
<h1>headline<br>
headline</h1>
<p>some text<br>
some text</p>
<p><a class="button" href="https://beyond-connect.com/anmeldung/">button</a></p>
</div>
Nothing fancy in the CSS:
.page-hero {
background-image: url(https://beyond-connect.com/wp-content/uploads/hero1.jpg);
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
padding-top: 10%;
padding-bottom: 15%;
}
For mobile devices I modified the padding a little bit, but that's it.
@media (max-width: 1080px) {
.hero {
margin-left: 0;
text-align: center;
}
.page-hero {
padding-top: 6%;
padding-bottom: 6%;
background-image: url("https://beyond-connect.com/wp-content/uploads/hero-mobil.jpg");
}
}
Thanks, Mike
Hi Mkjj,
That solution is alright.
You can also add .page-hero::after element and add the opacity through that. This is the more common solution I see.
If you use a GB Container Block instead through a Block Element - Page Hero, you can set that up with no code needed as well. Reference: https://docs.generateblocks.com/article/backgrounds-options-overview/#image
Thanks, Fernando. A pseudo-element was my first idea, but it didn't work. For test purposes, I've just removed the background image and added this CSS, but the image does not show:
.page-hero::after {
content: '';
background-image: url(https://beyond-connect.com/wp-content/uploads/hero1.jpg);
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
position: absolute;
top: 0;
left: 0;
width: 100%;
display: inline-block;
}
I don't use GB. I'm not a big fan of Gutenberg. :-)
Hi there,
try this CSS:
.page-hero::after {
content: '';
background-image: url(https://beyond-connect.com/wp-content/uploads/hero1.jpg);
background-size: cover;
background-position: center center;
background-repeat: no-repeat;
position: absolute;
width: 100%;
display: inline-block;
inset: 0;
z-index: -1;
left: 0;
}
Oh my, I'm such an idiot! Why did I forget the z-index? Works like a charm! Thank you, David. On Easter Monday!! :-)
As always: absolutely awesome support!
Glad to be of help :)