css - 响应式英雄图像作为 CSS 背景图像?

标签 css

对于我的响应式网站,我希望将英雄图片作为背景图片而不是 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

enter image description here

更新 - 背景大小的覆盖或包含不能解决我的问题。带有图像的 div 仍然具有固定的高度。

http://codepen.io/anon/pen/FCafi

enter image description here

最佳答案

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/

相关文章:

html - 是否有用于 html/css 验证的 IE 插件?

javascript - 无需大量剪切和粘贴的多张幻灯片

javascript - verticalAlign sub/sup 不工作

map 模板的CSS配置

javascript - 仅在选定区域(文本后面)模糊背景

jQuery 淡入淡出而不丢失容器空间

html - Bootstrap 折叠跳跃过渡,无填充/边距

HTML Flex 布局在 Internet Explorer 中看起来有所不同

html - div 和 ul 之间奇怪的垂直空间

javascript - 从右向左向下滚动时更改背景颜色