为什么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与主体分离开了,您实际上没有能力应用背景起源。

08-25 16:22
查看更多