Sh Najam
Sh Najam

Reputation: 21

Bootstrap carousel not working with background image

I want to add background image in my Bootstrap 4 carousel, but it is not working. I need help with the code.

<!-- The slideshow --> 
<div class="carousel-inner"> 
    <div class="active item one" style="background-image:url('1.jpg')">
    </div> 
    <div class="item two" style="background-image:url('2.jpg')">
    </div> 
    <div class="item three" style="background-image:url('3.jpg')">
    </div> 
</div>

Upvotes: 2

Views: 6368

Answers (2)

William
William

Reputation: 43

As mentioned in the comments, this happens because the carousel size depends on the image dimensions.

The easiest way to do that is by forcing the carousel dimensions. You can do that by adding the following code to your CSS:

.carousel,
.carousel-item,
.carousel-inner {
    height: 400px !important;
    width: 100% !important;
}

With this, the carousel height will be the one you chose (400px) and the carousel will fill the column, row or container where it was placed.

Upvotes: 0

dferenc
dferenc

Reputation: 8126

This is because the height of the carousel is determined by the height of .carousel-items, but without any content or an explicitly set height, the height of the slides is 0px. Note, that setting a background-image on an element does not set the height of it.

In order to make your carousel visible, you have to set the height of the .carousel-items. The example below makes use of the Embed utility classes to let .carousel-items have a 21:9 aspect ratio.

<div id="carousel" class="carousel slide" data-ride="carousel">
    <!-- Note the `embed-responsive embed-responsive-21by9` classes on the items wrapper -->
    <div class="carousel-inner embed-responsive embed-responsive-21by9">
        <!-- Carousel items have `.embed-responsive-item` -->
        <div class="carousel-item embed-responsive-item active" style="background-image:url('http://via.placeholder.com/525x225/adeee3/ffffff?text=1.jpg')">
        </div>
        
        <div class="carousel-item embed-responsive-item" style="background-image:url('http://via.placeholder.com/525x225/86deb7/ffffff?text=2.jpg')">
        </div>

        <div class="carousel-item embed-responsive-item" style="background-image:url('http://via.placeholder.com/525x225/63b995/ffffff?text=3.jpg')">
        </div>
    </div>
</div>


<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

Upvotes: 4

Related Questions