对于我的响应式网站,我希望将英雄图片作为背景图片而不是 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 仍然具有固定的高度。
http://codepen.io/anon/pen/FCafi
最佳答案
将 background-size: 100% 100%;
更改为 background-size: cover;
More on background-size:cover
from MDN
cover
This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.
注意。根据 Terry 的评论在下面,您可能还想添加 background-position: center center;
以确保图像保持居中。
关于css - 响应式英雄图像作为 CSS 背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23567620/