本质上,我想做的是在不直接在 CSS 中使用 background-url
的情况下创建一个“封面”效果。
我希望图像在移动状态下溢出并保持居中,同时容器高度保持固定在 600 像素。在仍然使用 img
标签的情况下这可能吗?
这是 pen使用以下代码:
<header id="carouselHome" class="carousel slide carousel-fade" data-ride="carousel">
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active"><img src="https://placehold.it/1500x600" /></div>
<div class="item"><img src="https://placehold.it/1500x600" /></div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carouselHome" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carouselHome" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</header>
对应的CSS:
.carousel {}
.carousel-inner {}
.carousel-inner .item {
height: 600px;
}
.carousel-inner .item img {
width: 100%;
height: auto;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.carousel-fade .carousel-inner .item {
opacity: 0;
transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
opacity: 0;
z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-control {
z-index: 2;
}
最佳答案
听起来像 css object-fit: cover;
可能适用于这种情况。 https://css-tricks.com/almanac/properties/o/object-fit/
请注意,旧版本的 IE 不支持此属性。此 polyfill 可能适用于 IE 回到版本 9。https://github.com/constancecchen/object-fit-polyfill
.carousel-inner .item img {
object-fit: cover;
width: 100%;
height: 100%;
}
关于css - 垂直居中图像并保持相同高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944759/