子边距不影响父高度 [英] Child margin doesn't affect parent height

查看:115
本文介绍了子边距不影响父高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



请跳转到真实问题,谢谢:)



但我发现它 - 这是问题描述:



问题:



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



HTML

 < div class =parent> 
< div class =child>一些文字...< / div>
< / div>

CSS

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

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



解决方案:



很简单,默认情况下,子边距通常不会影响父高度或父尺寸,通过在父元素中添加可以推到的边框可以很容易地固定,例如向父项添加填充或边框。



调整的CSS:

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

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



REAL问题:



但是我真的想知道为什么这样工作,不只是它是如何修复,

所以请,有人可以写一个解释这个行为,并添加一些DOC引用的答案?

非常感谢:)

解决方案

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


6.2。折叠边距



某些邻接边会合并形成一个边距。那些
的利润被称为崩溃。如果没有
非空的内容,填充或边界区域或清除分开
的边界,边界相邻。


有关示例的详细信息: http:// www.w3.org/TR/css3-box/#collapsing-margins



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



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


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

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

CSS

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

Fiddle: 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" to in parent element, e.g. add a padding or border to parent.

Adjusted CSS:

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

Fiddle: 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?

Many thanks :)

解决方案

It's called Collapsing margins. Documentation from 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.

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

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

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

这篇关于子边距不影响父高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆