为什么body
元素的可绘制区域包含边距?可以更改吗?
这是example(您也可以使用喜欢的编辑器):
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: url('http://www.w3schools.com/css/paper.gif') no-repeat;
border: 10px dashed red;
padding: 50px;
margin: 25px;
background-repeat: no-repeat;
background-origin: content-box;
}
h1 {
background: url('http://www.w3schools.com/css/paper.gif') no-repeat;
border: 10px dashed red;
padding: 50px;
background-attachment: scroll;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
如果比较这两个元素,则
background-image
元素的h1
不会填充空白区域,而body
元素会填充空白区域。如果我错过了CSS规范中的内容,您能帮我找到参考吗?我试图对
background-origin: content-box
使用body
来更改此行为,但这没有用。另外,如果删除
background-repeat
元素的h1
属性,那么它的background-image
也将延伸到其边界中,为什么会发生这种情况? 最佳答案
CSS中的边距设置了无法渲染元素的区域数量,因为它描述了边距。
此行为可以通过box model进行解释。
因此,如果将边距设置为25px,则意味着它不会让您绘制与该元素相关的任何内容。
我认为您正在寻找的代码(我假设)是:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 25px;
}
#content {
background:url('http://www.w3schools.com/css/paper.gif');
border: 10px dashed red;
padding: 50px;
background-repeat: no-repeat;
background-origin: padding-box;
}
h1{
background:url('http://www.w3schools.com/css/paper.gif') no-repeat;
border: 10px dashed red;
padding: 50px;
background-attachment: scroll;
}
</style>
</head>
<body>
<div id="content">
<h1>Hello World!</h1>
</div>
</body>
</html>
这会将您的CSS与主体分离开了,您实际上没有能力应用背景起源。