css3 – CSS:100%宽度和高度背景图像不起作用

作者:互联网

2026-03-27

HTML教程
我希望背景图像覆盖整个可用空间而不会被压扁. 实际上我认为背景大小是什么意思,但我想我做错了因为它不起作用,请帮助我.

HTML

Lorem Ipsum

CSS

body {    background-color: black;}.myDiv {    color: white;    background: url('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png') no-repeat center center fixed;     background-size: cover;}

小提琴http://jsfiddle.net/V7KSb/

只需使body和html 100%高度,同样为div

body, html{    height:100%;    padding:0;    margin:0;}.myDiv {    color: white;    background: url('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png') no-repeat center center fixed;     height:100%;    padding: 20px;    box-sizing: border-box;}

见小提琴:http://jsfiddle.net/V7KSb/5/

更新:给myDiv一些填充并使用box-sizing: border-box;以确保它不会超过100%.