Search code examples
bootstrap-4carousel

Add static vertically and horizontally centred caption (or other content) to Bootstrap 4's Carousel


In addition to the standard captions used by Bootstrap 4's carousel element, I'd like to overlay a static caption (or other content) in a responsive way over a full-screen carousel. I've found solutions (such as this one) for this which involve absolutely positioning a div and specifying a value for the top (eg 30%), however this only really works when you know the height of the static caption in advance.

I've been able to partially achieve this as below...

html:

<div id="carouselExampleIndicators" class="carousel slide carousel-fade" data-ride="carousel">
    <ol class="carousel-indicators">
        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
        ...
    </ol>
    <div class="carousel-inner" role="listbox">
        <div class="h-100 w-100 static-caption">
            <div class="d-flex text-center h-100">
                <div class="my-auto w-100 ">
                    <h1>Static caption here</h1>
                </div>
            </div>
        </div>
        <div class="carousel-item active" style="background-image: url('image.jpg');">
            <div class="carousel-caption d-none d-md-block">
                <h2 class="display-4">First Slide</h2>
                <p class="lead">This is a description for the first slide.</p>
            </div>
        </div>
        ...
    </div>
    <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"><span class="carousel-control-prev-icon"></span></a>
    <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"><span class="carousel-control-next-icon"></span></a>
</div>

css:

.carousel-item {
    height: 100vh;
    min-height: 350px;
    background: no-repeat center center scroll;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

.static-caption {
    position:absolute;
    z-index:1;
    pointer-events:none;
}

However, this feels a bit hacky (especially with z-index:1) and completely covers the carousel, making it impossible to click the controls (hence the pointer-events:none). Also it's 100% of the width, so the text overlaps the left/right controls. Reducing the width keeps the overlay left aligned and not centred.


Solution

  • Can you try the following code where your caption's class is carousel-caption

    .carousel-caption {
      width: 50%; height: 50%; left:25%; top:25%
    }
    

    **issue is resolved by the code snippet above.