> ` .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>
`
我在 CSS 函数中定义了轮播图像。代码可以工作,但是图片在浏览器上显示太大,因此需要上下移动滚动条。有没有办法让图像不滚动而适合?我需要根据每个图像的高度和宽度进行调整吗?
我不知道我是否正确理解了你的问题,但如果在这种情况下,轮播内的图像显示滚动,你可以使用轮播和
object-fit:cover
的最大高度(你可以检查哪个是最好的)对您来说有价值)图像中的属性。
重要提示:容器 div 需要属性 overflow: hidden
.box{
height: 300px;
width: 800px;
background-color: red;
overflow: hidden;
}
.carousel-inner {
max-height: 50px;
height:100%;
ho
}
.carousel {
display: flex;
}
.container {
max-height: 150px;
height: 90%;
}
.carousel-item {
position: relative
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.carousel-item img {
width: 100%;
object-fit: cover;
}
* {
box-sizing: border-box;
}
<div class="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="https://placehold.co/600x400" class="d-block w-100" alt="books_photo" />
</div>
</div>
</div>
</div>
</div>
问题
当幻灯片图像溢出并触发垂直滚动条出现时,就会出现问题。
解决方案
我们可以通过将图像的
max-height
设置为视口的 100% 来解决此问题。 Bootstrap 没有为此提供内置类,但我们可以创建一个:
.carousel-item img {
max-height: 100vh;
}
我们还需要通过将
text-center
添加到 carousel-item
来纠正副作用。这确保当宽度小于轮播时图像保持在轮播的中心。另一种方法(未显示)是显示全宽,但裁剪图像。
<div class="carousel-item text-center">
<img src="https://photojournal.jpl.nasa.gov/jpeg/PIA23685.jpg" class="img-fluid">
</div>
最终结果可以在片段中看到。单击“运行”,然后单击“整页”以调整页面大小并检查响应行为。
片段
.carousel-item img {
max-height: 100vh;
}
<div class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item text-center">
<img src="https://photojournal.jpl.nasa.gov/jpeg/PIA23685.jpg" class="img-fluid">
</div>
<div class="carousel-item text-center active">
<img src="https://photojournal.jpl.nasa.gov/jpeg/PIA24372.jpg" class="img-fluid">
</div>
<div class="carousel-item text-center">
<img src="https://photojournal.jpl.nasa.gov/jpeg/PIA23865.jpg" class="img-fluid">
</div>
</div>
</div>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/boo[email protected]/dist/js/bootstrap.bundle.min.js"></script>