所以,假设我们有一个“sky.jpg”背景图像和一个“sun.png”图像在它上面。
这是 HTML(5) 代码:
<div id="sky">
<img src="sun.png" id="sun">
</div>
这里是响应式 CSS:
#sky {
width:100%; /* width in percentage, so it will adapt to user's screen */
height:600px; /* here i've set a fixed height, but maybe it's not what you want */
background:url(sky.jpg) top center no-repeat;
text-align:center; /* #sun will be centered, not sure it's what you need */
background-size:cover;
-moz-background-size:cover;
}
#sun {
width:15%; /* adjust it to the needed ratio */
max-width:300px; /* max-width will prevent it from being bigger than the original image */
min-width:20px; /* min-width is optional */
}
Live demo(调整窗口大小)
注意background-size 属性设置为cover (more info here)。
表示将保留纵横比to the smallest size such that both its width and its height can completely cover the background positioning area。
这就是为什么您需要比大多数分辨率更大的图像(如果它是身体背景图像)。
此属性的其他可能值是“包含”和“自动”(have a look at the specs)。
background-size:cover; 是 not supported by IE8(这就是为什么我们仍然添加 top center 用于后台定位)并且对于某些 FF 版本,您需要供应商前缀 (-moz-)
现在您可以为#sun 设置百分比宽度,以便它与其包含的 div 保持比例。为了防止它变得比原来的尺寸大,你可以设置一个max-width(最后是min-width)。
图像的高度会在现代浏览器中自动调整。
如果您不想在 #sky 上设置固定高度,请确保其容器的高度也不同于 auto(默认值)。
例如,如果#sky 是您的页面背景图片,您必须设置:
html, body { height:100%; }
#sky { height:100%; }