为什么填充和边距不起作用?

时间:2018-06-01 14:20:22

标签: html css

我有以下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;
&#13;
&#13;

如您所见,虽然body设置为:

,但顶部有距离
  margin: 0;
  padding: 0; 

4 个答案:

答案 0 :(得分:1)

这是由于collapsing margins

基本上,p保证金与父div保证金相结合(然后再与body保证金相结合),以推动body

有(至少)3种方法可以解决这个问题:

  1. margin-top移除p,这会消除所有 p标记的余量。
  2. border-toppadding-top添加到容器(.box),这会产生添加您可能不需要的填充或边框的负面后果。
  3. overflow: [something] overflow: hidden添加到.box容器中,这可能导致以不希望的方式更改溢出。
  4. <!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;
}