Is there a better way to darken the background image?

I have the following code to darken the background image. Div with background image, then div inside what fills it with background color with transparency

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

And I flock this way

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

Does anyone know a more elegant solution?

+4
source share
2 answers

The only thing you can simplify is to lower the container .slide-overlayand add a pseudo-element ( :before, :after) instead .

Here is 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>
Run codeHide result

EDIT: The text below the pseudo-element is no longer dependent on the alpha channel of the overlay.

+6
source

You can also use several backgrounds:

.slide {
    background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)),                                            
                      url('/assets/img/bg-cover.jpg')
    background-size: cover
}
+1
source

Source: https://habr.com/ru/post/1598766/


All Articles