Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to darken a background image?

Tags:

html

css

opacity

I have the following code in order to darken a background image. A div with a background image then a div inside that which fills it with a background colour with transparency

<div class="slide">
  <div class="slide-overlay">
    <div class="slide-content">
      <h1>Blah blah content</h1>
    </div>
   </div>
</div>

And I am styling it like this

.slide
    background-image: url('/assets/img/bg-cover.jpg')
    background-size: cover
.slide-overlay
    background-color: rgba(0, 0, 0, .2)

Does anyone know of a more elegant solution?

like image 937
Clinton Green Avatar asked Mar 16 '23 08:03

Clinton Green


1 Answers

The only thing you could simplify is to omit the .slide-overlay container and by adding a pseudo-element (:before, :after) instead.

Here would be the solution for this:

.slide {
    background-color: tomato;
    background-size: cover;
}
.slide-content {
    position: relative;
    color: white;
}
.slide-content:nth-child(2):before, .slide-content:nth-child(3):before {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.2);
}
.slide-content:nth-child(3) {
    z-index: 1;
}
.slide-content:nth-child(3):before {
    z-index: -1;
}
<div class="slide">
    <div class="slide-content">
         <h1>No effects - just standard text.</h1>
    </div>
    <div class="slide-content">
         <h1>With overlay - text is below the overlay.</h1>
    </div>
    <div class="slide-content">
         <h1>With overlay - text is above the overlay.</h1>
    </div>
</div>

EDIT: Text below pseudo element is no longer affected by the overlay respectively alpha channel.

like image 79
F. Müller Avatar answered Mar 17 '23 21:03

F. Müller