html - CSS margin 恐怖; Margin 在父元素之外添加空间

标签 html css overflow margin

<分区>

我的 CSS 边距没有按照我想要或期望的方式运行。我的页眉边距顶部似乎影响了它周围的 div 标签。

这就是我想要和期望的: What I want....

...但这就是我最终得到的: What I get...

来源:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Margin test</title>

<style type="text/css">
body {
    margin:0;
}
#page {
    margin:0;
    background:#FF9;
}
#page_container {
    margin:0 20px;
}
h1 {
    margin:50px 0 0 0;
}
</style>

</head>

<body>

<div id="page">
    <div id="page_container">
        <header id="branding" role="banner">
            <hgroup>
                <h1 id="site-title"><span><a href="#" title="Title" rel="home">Title</a></span></h1>
                <h2 id="site-description">Description</h2>
            </hgroup>
        </header>
    </div>
</div>

我在这个例子中夸大了边距。 h1-tag 上的默认浏览器边距有点小,在我的例子中,我使用 Twitter Bootstrap,带有 Normalizer.css,它将默认边距设置为 10px。没那么重要,重点是;我不能、不应该、不想更改 h1 标签上的边距。

我想这和我的另一个问题类似; Why does this CSS margin-top style not work? 。问题是我该如何解决这个具体问题?

我已阅读 a few threads关于类似的问题,但还没有找到任何真正的答案和解决方案。我知道添加 padding:1px;border:1px; 可以解决问题。但这只会增加新的问题,因为我不想在我的 div 标签上添加填充或边框。

一定有更好的最佳实践解决方案吗?这一定很常见。

最佳答案

overflow:auto 添加到您的 #page div。

jsFiddle example

并查看 collapsing margins当你在做的时候。

关于html - CSS margin 恐怖; Margin 在父元素之外添加空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52145823/

上一篇:html - Bootstrap表格设置单元格宽度问题

下一篇:javascript - Bootstrap - 图像到 gif 到模态

相关文章:

HTML `dialog` 元素 : scroll content independently of background

python - 在 Python 中使用 0xFFFFFFFF 掩码检测 int32 溢出?

html - 垂直对齐菜单与表格显示

css - 如何去除ie6中png的阴影

javascript - 多步 jquery div 不显示数据

带有 Bootstrap 的 C# ASP.NET

html - 您将使用什么 CSS 规则来支持较小的屏幕和调整大小?

css - div 不随文本扩展

我的练习中出现 JavaScript 验证错误

javascript - 使用动态内容时调整 Div 的高度