> ` .carousel-inner {
height: 0;
padding-bottom: 60%; /* this sets carousel aspect ratio (4:1 here)50% adjust if image
gets cut off */
}
.carousel-item {
position: absolute !important; /* Bootstrap is insistent */
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.carousel-item img {
height: 100%; /* Bootstrap handles width already */
object-fit: contain; /* or 'contain',cover,fill,scale-down,none are examples if you
want stretch instead of crop https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
*/
}
* {
box-sizing: border-box;
<div class="container">
<div id="carouselExampleAutoplaying" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner ">
<div class="carousel-item active">
<img src="images/_1_early_history_and_stamp_1.jpg" class="d-block w-100"
alt="books_photo">
</div>
</div>
`
I defined the carousel image in a CSS function. Code works however the picture is showing too large on the browser thus causing the need to move the scroll bar up and down. Is there a way to make the image fit without scrolling? Would I need to make the adjustments at each image based on the height and width?
2
Answers
I don’t know if I understood your question correctly, but if in this case the image inside the carousel is showing the scroll, you can use a max height for the carousel and the
object-fit:cover
(you can check which is the best value for you) property in the image.Important: the container div need property
overflow: hidden
Problem
The problem happens when the slide images overflow and trigger the vertical scrollbar to appear.
Solution
We can fix this problem by setting the
max-height
of the images to 100% of the viewport. Bootstrap doesn’t have a built-in class for this, but we can create one:We also need to correct a side effect by adding
text-center
to thecarousel-item
. This ensures that the image remains centered in the carousel when the width becomes less than the carousel. The alternative (not shown) is to display full width, but crop the image.And the final result can be seen in the snippet. Click "Run" and then "Full page" to adjust the page size and check responsive behavior.
Snippet