Apply "Background-Size:Cover" to Twitter Bootstrap Carousel Slides

Bootstrap carousel, with cover images and indicators

If you are OK with using background images, you could use the CSS property background-size: cover to make the background image cover the entire carousel slide div. Then your text would also be inside the slide div and sit on top of the background image. You can read more about background-size here.

Here is a Fiddle demonstrating the use of background images with background-size: cover.

If you need the images to load in img tags, then you could use this solution that uses JavaScript to determine if the image is wide or tall, and then applies the appropriate CSS styling.

let carousel images cover their div

Firstly I'd definitely overwrite bootstrap's styles in another CSS file because it allows you to update Bootstrap in the future without losing any changes you've made.

The way I'd tackle this is by adding a fixed height to the carousel/items (which can be changed for different breakpoints) as it's easier to deal with the image this way.

Then make the img absolutely positioned relative to the .item. You can then center the image vertically using transform should you want to.

CSS

.carousel-inner > .item {
height: 30em;
}

.carousel-inner > .item img {
height: auto;
position: absolute;
top: 0;
transform: translateY(-50%);
width: 100%;
}

You'll still have some cropping issues with square images on a wide viewpoint but there's not a huge amount that can be done about that. You can, however, tweak the amount the image is shown by adjusting the .item height or its position by tweaking the transform style.

Full example: https://codepen.io/raptorkraine/pen/aLOwOQ

Background-size: cover not working in Bootstrap 4

You can give background-size property if there is a background-image. In your case you have used an img tag so instead for the img tag use this properties:

width: 100%;
height: 250px;
object-fit: cover;

where you can give height as the height you desire to have.

How to fully fit an image inside carousel(Bootstrap)

Set Image width:100%

.item img {
width:100%
}

Here is Demo: https://jsfiddle.net/u9kkdLzb/



Related Topics



Leave a reply



Submit