Hacking the Bootstrap 5 Carousel: Consistent Height Carousels with CSS Gradients and Object Fit
Ray Villalobos
The Bootstrap carousel is one of the most popular components in Bootstrap 5, but we have the technology to improve it and at the same time learn about one of my favorite new CSS features object-position and object-fit.
This is Part One of a three part series on Hacking the Bootstrap Carousel. This part focuses on simple CSS to make the carousel have a consistent height and a gradient so that different sized images can look great within the same carousel.
Here's the problem. The documentation tells you to add an image with a class of d-block w-100 That means that it will shrink or stretch the image to whatever height will fit in the width. But what if the images aren't exactly the same height or proportions?
To fix this we can use some newer CSS properties that you may have not heard of. If you're familiar with how backgrounds work, you know that you can set the background-size attribute to cover and it proportionally resize the background to fit the space available.
You can do the same thing with a regular image using a CSS property called object-fit. To get this to look right, you can combine it with object-position to center the image.
Another problem happens when you want to put some text on top of an image, but the color of the image and the text are too similar, so the text disappears.
LInks in this video:
Object Fit: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
Object Position: https://developer.mozilla.org/en-US/docs/Web/CSS/object-position
Before Pseudo Element: https://developer.mozilla.org/en-US/docs/Web/CSS/::before
Can I Use: https://caniuse.com/?search=object-fit, https://caniuse.com/?search=object-position
Article with all the code: https://raybo.org/posts/2021-03-27-consistent-height-carousels-with-css-gradients-by-hacking-the-bootstrap-5-carousel/
Part 2: Building Sidebar Carousels: https://raybo.org/posts/2021-03-28-making-sidebar-carousels-with-css-by-hacking-the-bootstrap-5-carousel/
Part 3: Automating Arrows and Indicators with JavaScript: https://raybo.org/posts/2021-03-29-automating-the-creation-of-carousel-features-with-javascript-by-hacking-the-bootstrap-carousel/ ... https://www.youtube.com/watch?v=KHF6nysy0-c
30443866 Bytes