首页 > 解决方案 > 这里有什么理由吗?

问题描述

<!DOCTYPE html>
<html>
    <head>
        <style>
            #one{
                background-color: brown;
                text-align: center;
                margin-top: 0;
            }
            #two{
                background-color: rgb(86, 74, 153);
                text-align: center;
                margin-top: 0;
            }
        </style>
    </head>
    <body>
        <div id="one">
            <h1>heading</h1>
        </div>
        <div id="two">
            <h2>welcome section</h2>
        </div>
    </body>
</html>

为什么在这里margin-top: 0margin-bottom: 0不是在css中工作?在 css 中有这样的规则吗?如果我给两者都加上边框,它就可以工作。同样,当我给出 1px 的边框时,div 的高度会自动增加,边距变为零,但没有边框我不能将边距设置为零。为什么?请简要说明这条规则。

标签: htmlcss

解决方案


h元素具有默认边距。你的h1h2导致它。

#one h1, #two h2 {
   margin-top:0;
   margin-bottom:0;
}

推荐阅读