css设置时父元素随子元素margin值移动

父元素的盒子包含一个子元素盒子,给子元素盒子一个垂直外边距margin-top,父元素盒子也会往下走margin-top的值,而子元素和父元素的边距则没有发生变化。

HTML,CSS:

<div class="box1">
    <div class="box2">
        <div class="content">
            <div class="margin">123</div>
        </div>
    </div>
</div>
*{padding:0; margin:0;}
.box1{ width:600px; height:1042px; margin:0 auto; background:#ccc; overflow:hidden;}
.box2{ width:600px; height:1042px; background:#000; overflow:hidden;}
.content{ width:600px; height:1042px;  overflow:hidden;}
.margin{ width:400px; height:30px; line-height:30px; text-align:center; margin:20px; background:#f00;  overflow:hidden;}

解决方法:

1、修改父元素的高度,增加padding-top样式模拟(padding-top:1px;常用) 
2、为父元素添加overflow:hidden;样式即可(完美) 
3、为父元素或者子元素声明浮动(float:left;可用) 
4、为父元素添加border(border:1px solid transparent可用) 
5、为父元素或者子元素声明绝对定位

posted on 2017-06-11 22:33  aivnfjgj  阅读(192)  评论(0编辑  收藏  举报

导航