html - 标题、导航中的边距为 0

标签 html css margin

设置 margin: 0 不在 header{}nav{} 中,但在 ul{} 中按预期工作。我认为 ul{margin:0} 不会起作用,因为 headernav 是父级。

<head>
    <meta charset="UTF-8">
    <title>Compañía</title>
    <link rel="stylesheet" href="estilo.css"> </head>

<body>
    <header>
        <nav>
            <ul>
                <li><a href="#">About</a></li>
                <li><a href="#">Products</a></li>
                <li><a href="#">Purchase</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </header>
</body>

</html>

body {
    margin: 0;
    padding: 0;
}

header {
    background-color: darkseagreen;
    height: 420px;
    margin: 0;
    padding: 0;
}

nav {
    margin: 0;
}

Link to example image

最佳答案

那是因为您看到的边距来自 ul,而不是 headernav。默认情况下,headernav 的边距都为 0,因此向其中任何一个添加 margin: 0; 都不会执行任何操作。但是,ul 具有浏览器应用的默认边距,因此设置 ul { margin: 0; } 删除默认边距。

由于 margin collapse,您看到 ul 的边距超出了它的父级边界

If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

关于html - 标题、导航中的边距为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183721/

相关文章:

用于多项选择测验的 Javascript

javascript - 如何使用 alt 更改 img 的 src?

php - 单击刷新 div 中的页面

css - 溢出 :hidden messing with margins in Chrome and Safari

html - 如何通过CSS更改图像覆盖整个div

html - 如何强制流体 DIV 扩展到全部可用宽度?

html - 如何使用 ngFor 和表格 [Angular] 显示矩阵元素

css - 防止内联 div 在容器被截断时换行

java - 如何使 JSliders 仅显示四肢

jQuery:当 slider 表单从顶部向下滑动时