为什么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
不会填充边距区域,而{I}元素则会填充该区域。如果我在CSS规范中错过了这个,你能帮我找一个参考吗?
我尝试使用body
background-origin: content-box
更改此行为,但这不起作用。
此外,如果我删除body
元素的background-repeat
属性,那么其h1
也会延伸到其边框,为什么会发生这种情况?
答案 0 :(得分:0)
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从身体中分离出来,而您实际上无法应用背景来源。
答案 1 :(得分:0)
在一些俄罗斯的顶级秘密核火箭地下室找到解决方案:你应该将CSS标签设置为HTML标签,然后一切,包括身体的背景图像将移动:
<!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;
}
html{
margin-top: 40px;
margin-left: 20px;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>