CSS 子边距不影响父高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27829250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:53:33  来源:igfitidea点击:

Child margin doesn't affect parent height

css

提问by jave.web

This might be obvious for some, but I found it hard to find the solution for this.

这对某些人来说可能很明显,但我发现很难找到解决方案。

Note for answer-ers:please jump to "The REAL question", thanks :)

回答者注意:请跳到“真正的问题”,谢谢:)

But I found it - it is below description of the problem:

但我找到了 - 它在问题的描述下面:

The problem:

问题:

In simple example like this one the child margin does not affect parent height

在这样的简单示例中,子边距不会影响父高度

HTML

HTML

<div class="parent">
    <div class="child">Some text...</div>
</div>

CSS

CSS

.parent{ background: black; }
.child{
    background: LightBlue;
    margin: 20px;
}

Fiddle: http://jsfiddle.net/k1eegxt3/

小提琴:http: //jsfiddle.net/k1eegxt3/

The solution:

解决方案:

Is quite simple, by default, child margins do not affect parent height respectively parent dimensions in general, it is easily fixed by adding something that margin could "push" toin parent element, e.g. add a padding or border to parent.

很简单,默认情况下,子边距通常不会影响父高度和父尺寸,通过在父元素中添加边距可以“推”到的东西很容易修复,例如父元素添加填充或边框。

Adjusted CSS:

调整后的 CSS:

.parent{ background: black; padding: 1px; /* PADDING ADDED */ }
.child{
    background: LightBlue;
    margin: 20px;
}

Fiddle: http://jsfiddle.net/fej3qh0z/

小提琴:http: //jsfiddle.net/fej3qh0z/

The REAL question:

真正的问题:

However I actually want to know why does this work this way, not just how it is fixed,
so please, could someone please write an answer explaining this behaviour and add some DOC references?

但是我实际上想知道为什么会这样工作,而不仅仅是它是如何修复的,
所以拜托,有人可以写一个解释这种行为的答案并添加一些 DOC 引用吗?

Many thanks :)

非常感谢 :)

回答by Key-Six

It's called Collapsing margins. Documentation from www.w3.org:

它被称为折叠边距。来自 www.w3.org 的文档:

6.2. Collapsing margins

Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.

6.2. 折叠边距

某些相邻的边距结合起来形成一个边距。这些利润被称为“崩溃”。如果没有非空内容、填充或边界区域或间隙来分隔它们,则边距是相邻的。

More information with examples: http://www.w3.org/TR/css3-box/#collapsing-margins

更多示例信息:http: //www.w3.org/TR/css3-box/#collapsing-margins

You can add overflow: auto;to the parent element to fix this.

您可以添加overflow: auto;到父元素来解决此问题。

Fiddle: http://jsfiddle.net/k1eegxt3/2/

小提琴:http: //jsfiddle.net/k1eegxt3/2/

回答by Samed VS

Add display: flex; to parent element adjust flex direction, align and justify as you want but the margin thing with appear as you want.

添加显示:flex;到父元素调整 flex 方向,根据需要对齐和对齐,但边距会根据需要显示。