简单的HTML问题解释

时间:2014-06-30 01:10:39

标签: html css

几年前,当我第一次学习HTML时,我注意到了这种奇怪的行为,但仍然不理解它。

两个jsfid都基于以下HTML:

<div class="parent">
    <div class="child">
        Child content
    </div>
</div>

在第一个jsfiddle中,我在子元素中添加了margin-top,但整个父元素向下移动:http://jsfiddle.net/flyingL123/uUgVz/

在下一个jsfiddle中,我唯一要改变的是向父元素添加边框,现在父元素不再向下移动页面:http://jsfiddle.net/flyingL123/uUgVz/1/

为什么两个jsfid都没有表现相同?在父元素没有边框的情况下,为什么父元素受子元素上的margin-top影响?

3 个答案:

答案 0 :(得分:0)

这是因为child不是empty 身高!== 0

<div class="parent">
    <div class="child">
        Child content
    </div>
</div>

相同
<div class="parent">
    <div></div>
    <div class="child">
        Child content
    </div>
</div>

空元素将用作包装器

enter image description here

并为parent添加边框就像是说嘿现在我们想要看到的内容与添加字母相同:

<div class="parent">
    m
    <div class="child">
        Child content
    </div>
</div>

-Demo-

请注意,您正在parent元素上应用样式而不是child, that means the first and all next not空子if they don t样式集将采用父样式

答案 1 :(得分:0)

它与如何呈现block元素有关。默认情况下,div不会隐藏其内容,这意味着div内部的任何内容都会超出其父级,就像子元素的边距一样,但是您可以使用overflow: hidden属性因此,内容仅限于容器的大小,从而使你的余量从div的内部推出,因为它不会突然出现:

请参阅the updated fiddle

<强> CSS

.parent{
    width:300px;
    background-color:#666;
    color:white;
    overflow: hidden;
}

.child{
    margin-top:50px;
}

但是如果你仍然希望孩子们伸出父母而不是被推下来,你可以设置容器的padding值而不是孩子的margin值,参见{{3} }:

<强> CSS

.parent{
    width:300px;
    background-color:#666;
    color:white;
    padding-top: 50px;
}

.child{
    /* margin-top:50px; */
}

答案 2 :(得分:0)

您描述的效果是由 Margin Collapsing

引起的

完成此Stackoverflow以了解如何删除边距折叠。