我有以下html页面:
<!DOCTYPE html>
<html>
<head>
<style>
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
.box {
height: 100%;
background-color: brown;
}
</style>
</head>
<body>
<div class="box">
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
</body>
</html>
&#13;
如您所见,虽然body
设置为:
margin: 0;
padding: 0;
答案 0 :(得分:1)
这是由于collapsing margins。
基本上,p
保证金与父div
保证金相结合(然后再与body
保证金相结合),以推动body
。
有(至少)3种方法可以解决这个问题:
margin-top
移除p
,这会消除所有 p
标记的余量。border-top
或padding-top
添加到容器(.box
),这会产生添加您可能不需要的填充或边框的负面后果。overflow: [something]
overflow: hidden
添加到.box
容器中,这可能导致以不希望的方式更改溢出。
<!DOCTYPE html>
<html>
<head>
<style>
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
}
.box {
/* padding-top on the container is one solution */
padding-top: 1px;
height: 100%;
background-color: brown;
}
</style>
</head>
<body>
<div class="box">
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
</body>
</html>
答案 1 :(得分:1)
这是突破DIV的p
元素的默认边距(&#34;折叠边距&#34;)。如果您为margin: 0
设置p
,它将会消失,但是,p
元素之间的垂直距离会更短。
答案 2 :(得分:0)
默认情况下,段落内置了填充,您可以使用内联样式覆盖它,也可以通过执行全局默认值来指定Paragraphs不应该填充。
<head>
<style>
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
.box {
height: 100%;
background-color: brown;
}
</style>
</head>
<body>
<div class="box">
<p style='margin:0; padding:0;'>This is a paragraph.</p>
<p style='margin:0; padding:0;'>This is a paragraph.</p>
</div>
</body>
</html>
确保边距和填充。
OR ......
如果您不想这样做内联更改您的样式定义,请在现有的.box {}类之后添加它:
.box p {
margin:0; padding:0;
}
这将把风格应用于所有&#34; P&#34;类框中的标签
答案 3 :(得分:0)
您可以设置.box
的填充顶部.box {
padding-top: 1rem;
}