引导程序更改轮播高度

34

我这里有一个jsfiddle-http://jsfiddle.net/gh4Lur4b/8/

这是一个全宽度的Bootstrap轮播。

我想改变高度但仍然保持全宽度。

高度是由图片高度决定的吗?

如何改变轮播的高度并保持100%的宽度?

.carousel-inner{
    // height: 300px;
}

.item, img{
    height: 100% !important;
    width:  100% !important;
    border: 1px solid red;
}

你在问题中打错了字。 - Muhammad Abdullah
减小文件大小的最佳方法是改变图像的高度。 - CONTENT
7个回答

38
以下应该能正常工作。
.carousel .item {
  height: 300px;
}

.item img {
    position: absolute;
    top: 0;
    left: 0;
    min-height: 300px;
}

JSFiddle 供参考。


这不会改变图像的大小。轮播图的大小会改变,但图像不会。我想我希望有类似于 background-size:cover; 的东西,这样图像就可以被拉伸了。http://jsfiddle.net/gh4Lur4b/17/ - ttmt
哦,我明白你的意思了。很抱歉从你最初的问题中没有看出来。请查看我的更新答案。 - Bart Jedrocha
但是现在当窗口变小时,图像被压缩了。在您的jsfiddle中,当窗口变大时,图像不会被拉伸,而是扩展。我需要在窗口变小时获得类似的效果。 - ttmt
你知道这些图片吗?换句话说,你能否在你的CSS中访问它们? - Bart Jedrocha
此外,如果���将50%作为高度使用,则似乎此方法无法正常工作。有人知道如何解决吗?谢谢。 - HumbleWebDev

17

你可能也想添加

object-fit: cover;
为了保持不同窗口尺寸的宽高比。
.carousel .item {
  height: 500px;
}

.item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

对于Bootstrap 4及以上版本,请将.item替换为.carousel-item

.carousel .carousel-item {
  height: 500px;
}

.carousel-item img {
    position: absolute;
    object-fit: cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

2
仅针对Bootstrap 4(我没有查看旧版本),您肯定是指 .carousel .carousel-item { height: ..... } 而不是 .carousel .item,对吗? - Reversed Engineer
优秀的答案是在Bootstrap 4及以上版本中,将.item替换为.carousel-item,正如上面的注释所说。 - Bobby Axe

10

来自Bootstrap 4

.carousel-item{
    height: 200px;
} 
.carousel-item img{
    height: 200px;
}

1

如果有人来到这里寻找标题所指的内容,这将有所帮助(记住,在Bootstrap v4中使用jQuery是可以的):

$.fn.normalizeHeight = function () {
    $(this).css("height", Math.max.apply(null, $(this).children().map(function () {
        return $(this).height();
    })) + "px");

    return this;
};

这个函数可以简单地通过以下方式调用:

$("#slider .carousel-inner").normalizeHeight();

$(window).on('resize', function () {
  $("#slider .carousel-inner").normalizeHeight();
});

它符合ES5标准,同时能够在需要等高子元素的情况下正常工作。

1
like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows

.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}

@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
 }
}

-2
尝试以下代码,应该可以正常运行:
.carousel .carousel-item {
    max-height:550px;
}

.carousel-item img {
    object-fit:cover;
    max-height:550px;
}

-2

针对Bootstrap 4

在相同的行内添加图片 添加 height: 300px;

<img src="..." style="height: 300px;" class="d-block w-100" alt="image">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接