教程英文原版https://css-tricks.com/perfect-full-page-background-image/
我们的目标是让一张背景图能够覆盖整个浏览器窗口,在做之前,先提一下对最后效果的要求:
- 图片要填充整个窗口,没有边距;
- 根据需要缩放图片
- Retains image proportions (aspect ratio)[保持图像的比例(纵横比)]
- 图片居中于页面
- 不要造成任何scrollbar
- 尽可能多的浏览器兼容
- Isn’t some fancy shenanigans like Flash
使用 CSS3 中的 background-size
属性,我们可以以纯CSS的方式来实现这个效果。我们将使用HTML元素(而不是 body,因为它的高度经常会比浏览器窗口的高度低)。我们在其上设置一个固定居中的背景,然后设置 background-size 属性为cover
来调整它的大小。
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
注意这个时候背景图片覆盖整个html,我们可以设置透明的文字来达到一种不错的效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Full Page Background Image | Progressive</title>
<style>
* { margin: 0; padding: 0; }
html {
background: url(image/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#page-wrap {
width: 400px;
margin: 50px auto;
padding: 20px;
background: white;
opacity: 0.8;
-moz-box-shadow: 0 0 20px black;
-webkit-box-shadow: 0 0 20px black;
box-shadow: 0 0 20px black;
}
p { font: 15px/2 Georgia, Serif; margin: 0 0 30px 0; text-indent: 40px; }
</style>
</head>
<body>
<div id="page-wrap">
<h1>Architecture</h1>
...
</div>
</body>
</html>
对于让IE如何更好的实现这个效果原文中有一些讨论,这里就不在赘述