对于我的响应网站,我想将英雄图像作为背景图像而不是html中的图像。
我可以轻松地使div的宽度为100%,但是我不确定如何使它具有正确的高度。我必须以px为单位设置高度,但是所需的高度取决于div的宽度,该宽度随站点的响应而变化。
<div class="cont">
<p>Below is an image in the html that scales correctly</p>
<img src="http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg" />
<p>The example below is a background image in CSS</p>
<div class="hero-img"></div>
<p>Some text</p>
</div>
.cont {
width: 20%;
margin: auto
}
img {
max-width: 100%;
}
.hero-img {
background: url("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg") no-repeat;
background-size: 100% 100%;
height: 200px;
}
http://codepen.io/anon/pen/FBxkz
更新-背景尺寸的封面或包含内容无法解决我的问题。具有图片的div仍然具有固定的高度。
更改background-size: 100% 100%;
为background-size: cover;
有关background-size:cover
MDN的更多信息
盖
此关键字指定背景图像应缩放到尽可能小,同时确保其尺寸都大于或等于背景定位区域的相应尺寸。
nb。根据下面Terry的评论,您可能还需要添加background-position: center center;
以确保图像保持居中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句