如何将图像100%适配Jumbotron

11

我有以下的HTML:

<div class="jumbotron">
    <div class="container">
        <h1>Souplesse</h1>
        <p>Be a Good Sport</p>
    </div>
</div>

并且以下是CSS:

.jumbotron {
  background-image:url('piscine.jpg');
  height:300px;
  background-repeat: no-repeat;
  background-size: cover;
  border-bottom:1px solid #ff6a00
}
.jumbotron .container {
  position:relative;
  top:50px;
}

我的图片太大了,不能适应我设置的300像素的高度,但我希望它可以自动缩放并适应高度,这样我就可以看到整张图片。这应该很简单,但我不知道需要做哪些更改。

谢谢

2个回答

33

如果希望背景图像适应 jumbotron 的高度,但不在意是否延伸到整个宽度:

.jumbotron { background-size: auto 100%; }

如果希望背景图像覆盖 jumbotron 的整个高度和宽度,并且不在意图像的纵横比:

.jumbotron {background-size: 100% 100%; }

如果希望背景图像覆盖 jumbotron 的整个高度和宽度,并且在意图像的纵横比:

.jumbotron { background-size: cover; }

最后一个选项将会剪切一些图像,如果 jumbotron 的纵横比与图像不同,但您可以使用 background-position 属性指定图像的位置:

.jumbotron {
    /* Image in the center of container */
    background-position: center center;

    /*  OR Image in the center top of the container */
    background-position: center top;

    /*  OR Image in the center bottom of the container  */
    background-position: center bottom;
}

1
谢谢Pete,这涵盖了所有基础知识,是一些非常优秀的知识。感谢分享。 - jmn8
我的问题在于使用“覆盖”时,当客户希望整个图像始终以100%的宽度可见时。目前我正在处理一个页面,其中图像宽度跨越整个浏览器,但在大屏幕上查看时,图像底部会被裁剪掉。 - user3120861
如果你不想让图片被裁剪或拉伸,并希望它在容器内尽可能地放大,那么background-size: cover; 可能是一个很好的选择。 - Pete Droll

0

尝试:

.jumbotron {
  background-image:url('piscine.jpg');
  height:300px;
  background-repeat: no-repeat;
  background-size: auto 100%;
  border-bottom:1px solid #ff6a00
}

请注意:

background-size: auto 100%;

第一个值是宽度,第二个值是高度。可以使用px或%来表示这些值。


这种方法有一定作用,但是当你在页面上放大或缩小(至少在我使用的Chrome浏览器中)时,你会发现图片不再适合。 - jmn8

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