Search code examples
cssbootstrap-4

Darkening a background image on a bootstrap carousel


I'm having trouble formatting my images to be darker in order to read the text on them. I'm using the bootstrap carousel theme and can't get the images darkes! Opacity works but it makes the text more transparent also. As far as I know the linear-gradient should be working but nothing is happening. I have tried it on all the classes (not just image class slide).

.slide {
  background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7));
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="carousel-inner" role="listbox">
  <div class="item active">
    <img class="slide"  src="http://placehold.it/800x300" alt="First slide">
    <div class="container">
      <div class="carousel-caption">
        <h1>Welcome to GroupWrites.</h1>
        <p>Where creative writing meets social media. Discover our community of writers and readers and experience social writing. </p>
        <p><a class="btn btn-lg btn-primary" href="/register" role="button">Sign up today</a></p>
      </div>
    </div>
  </div>
</div>


Solution

  • You set the background of the <img> element but this isn't working because the background is only visible in case the image is transparent or missing. You can use :after or :before to create a new overlay on top of the image with a semi transparent background using rgba.

    You can use the pseudo-class on .item or .carousel-inner to darken the image without affecting the text.

    .item:after {
      content:"";
      position:absolute;
      top:0;
      bottom:0;
      left:0;
      right:0;
      background:rgba(0,0,0,0.6);
    }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img class="slide" src="http://placehold.it/800x300" alt="first slide">
        <div class="container">
          <div class="carousel-caption">
            <h1>Welcome to GroupWrites.</h1>
            <p>Where creative writing meets social media. Discover our community of writers and readers and experience social writing.</p>
            <p><a class="btn btn-lg btn-primary" href="/register" role="button">Sign up today</a></p>
          </div>
        </div>
      </div>
    </div>