margin塌陷和margin合并问题及解决方案

margin塌陷

先举个例子

<style>
        body{
            background-color:#000;
        }
     .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
     }
     .box{
        width:50px;
         height:50px;
         background-color:#eee;
         opacity:0.8;
     }
    </style>
</head>
<body >
        <div class="wrapper">
            <div class="box"></div>
        </div>
</body>

距离上边100px;

现在给里面的小方块设置margin-top:100px;发现两个方块位置没动;

而当给里面的小方块设置margin-top:150px;小方块带着大方块往下移动了50px

原理:父子嵌套元素在垂直方向的margin,父子元素是结合在一起的,他们两个的margi会取其中最大的值.

正常情况下,父级元素应该相对浏览器进行定位,子级相对父级定位.

但由于margin的塌陷,父级相对浏览器定位.而子级没有相对父级定位,子级相对父级,就像坍塌了一样.

 

margin塌陷解决方法

1.给父级设置边框或内边距(不建议使用)

 .wrapper{
         width:200px;
         height:200px;
         background-color:red;
         margin-top:100px;
         border-top:1px solid black;
     }

 

2.触发bfc(块级格式上下文),改变父级的渲染规则

方法:

改变父级的渲染规则有以下四种方法,给父级盒子添加

(1)position:absolute/fixed

(2)display:inline-block;

(3)float:left/right

(4)overflow:hidden

这四种方法都能触发bfc,但是使用的时候都会带来不同的麻烦,具体使用中还需根据具体情况选择没有影响的来解决margin塌陷

 

 margin合并

原理:两个兄弟结构的元素在垂直方向上的margin是合并的

html

1  <div class="box1"></div>
2  <div class="box2"></div>

 

css

        *{
            margin: 0;
            padding: 0;
        }
        body {
            background-color: #000;
        }
        .box1 {
            height: 30px;
            margin-bottom: 100px;
            background-color: red;
        }
        .box2 {
            height: 30px;
            margin-top: 100px;
            background-color: aqua;
        }

margin合并问题也可以用bfc解决,

1.给box2加上一层父级元素并加上overflow:hidden;

  <div class="box1"></div>
   <div class="wrapper">
        <div class="box2"></div>
  </div>
.wrapper{
            overflow:hidden;
        }

2.给两个都加一层父级再加bfc

    <div class="wrapper">
        <div class="box1"></div>
    </div>
    <div class="wrapper">
        <div class="box2"></div>
    </div>

但是这两种方法都改变了HTML结构,在开发中是不能采用的

所以在实际应用时,在margin合并这个问题上,我们一般不用bfc,而是通过只设置上面的元素的margin-bottom来解决距离的问题

 

posted @ 2018-07-27 14:15  StupidTom  阅读(13132)  评论(0编辑  收藏  举报