HTML中h1标签的边距推动了其容器的缩减

时间:2015-11-20 16:40:33

标签: html css margin

请看下面的图片。我不知道为什么标题(蓝色块)已经下降了一点点。我的意思是,蓝色块应该完全触及浏览器内容区域的末尾。有人告诉我那是因为h1的边缘。但我认为这个边际只会导致h1在蓝色区块内略微下降,而不是让整个蓝色区块下降。谁能帮我?非常感谢!

enter image description here

很抱歉,代码现已添加到下方。

<!DOCTYPE html>
<html>
<head>
<title>just for test</title>
<style>
    body,html {
        margin: 0;
    }

    header {
        background-color: blue;
        height: 200px;
        width: 1200px;
        margin: 0 auto;
        text-align: center;
        padding: 0;
    }

    h1 {
        color: white;

    } 

</style>
</head>
<body>
    <header>
        <h1>Why does it have to be like this?</h1>
    </header>
</body>
</html> 

2 个答案:

答案 0 :(得分:1)

这里有一个简单的例子。

以下代码返回以下结果:

Margins

<h1 class="nomargins">Testing 1</h1>
<h1 class="margins">Testing 2</h1>
.margins {
  width: 500px;
  height:200px;
  background-color:#0000ff;
  float:left;
}

.nomargins {
  width:500px;
  height:200px;
  margin: 0;
  background-color:#ff0000;
  float:left;
}

注意唯一的区别是颜色和边距。

答案 1 :(得分:0)

这是利润率下降的问题。 h1 标记,其中包含一些文本,并包装在标头指定的容器中。现在 h1 标签未将其margin-top放入容器内,并且由于发生边距倒塌问题,由于默认边距拉低了整个容器(因为 h1 标签折叠为0)。如果您说h1应该在容器内有边距,那么您需要在padding,border,display:inline-block内使用overflow: autoheader {}属性

在从上面的列表中提供任何一个属性后,您可以防止 h1 标签的边距崩溃,并且 h1 标签所包含的文本将在容器内具有边距并且会得到公正对待此 h1 标签的边距将不会受到损害。

我知道,您给了padding但值为0,所以它不起作用。您必须给它一些价值。