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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With