Journal

How do you fade a Bootstrap 4 carousel instead of sliding it?

Add the class carousel-fade and a short stylesheet that crossfades the slides instead of translating them. The markup below is the Bootstrap 4 pattern from a note first published on April 19, 2018. It is here for themes that still run Bootstrap 4. Bootstrap 5 changed the carousel markup and dropped the jQuery dependency, so do not paste this into a Bootstrap 5 project and expect it to match the docs.

I have never liked the default slide. The motion is abrupt. A fade is calmer, and it is still a carousel, which means it still moves while someone is trying to read. Use it when a design insists on one.

The captions in the original example sat on top of the photographs. To keep the type readable I put a black background on the carousel and lowered the image opacity in CSS. The 2018 prose said the images were fully opaque. The stylesheet said otherwise. The stylesheet is the one that shipped, and it is the one below.

Bootstrap’s CSS and JavaScript have to be loaded by the theme already. This snippet does not include them.

<div id="carouselExample" class="carousel carousel-fade">
  <ol class="carousel-indicators">
    <li data-target="#carouselExample" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExample" data-slide-to="1"></li>
    <li data-target="#carouselExample" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="image.jpg" alt="Describe the first slide">
      <div class="carousel-caption d-md-block">
        <h2>Title</h2>
        <p class="lead">Lead text</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="image.jpg" alt="Describe the second slide">
      <div class="carousel-caption d-md-block">
        <h2>Title</h2>
        <p class="lead">Lead text</p>
      </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="image.jpg" alt="Describe the third slide">
      <div class="carousel-caption d-md-block">
        <h2>Title</h2>
        <p class="lead">Lead text</p>
      </div>
    </div>
  </div>
</div>
#carouselExample { background-color: #000; }

.carousel.carousel-fade .carousel-item {
  display: block;
  opacity: 0;
  transition: opacity ease-out 1.7s;
  left: 0;
  top: 0;
  position: absolute;
}

.carousel.carousel-fade .carousel-item.active {
  opacity: 1;
}

.carousel.carousel-fade .carousel-item:first-child {
  top: auto;
  position: relative;
}

.carousel img { opacity: 0.5; }

Give every image a real alt. The decorative ones can be empty only when the caption next to them already says the same thing, and even then a short description is usually the better choice.

If the carousel is the reason the page feels slow, the more useful project is performance work, not a smoother transition.