bfc和两个经典bug

2019-01-07  本文已影响0人  DARKSIIIDE

一、触发bfc(block format context块级格式化上下文)

css把html的每一个元素都当成一个盒子,并且认为每个盒子都有一套渲染规则,每一个盒子里都有一套一模一样的语法规则,触发bfc就是通过一些特定的手段,让其中的几个或者一个盒子里面的渲染规则发生改变,改变的程度只有一点点,可以解决两个经典Bug。

二、如何触发一个盒子的bfc

position:absolute;绝对定位
display:inline-block;行间块级元素
float:left/right;浮动
overflow:hiden;溢出盒子的部分要隐藏展示

三、margin塌陷bug

HTML

<div class="wrapper">
    <div class="content"></div>
</div>

CSS

1.小于等于父元素设定的margin值时
.wrapper{
    margin-left: 100px;
    margin-top: 100px;
    width: 100px;
    height: 100px;
    background-color: black;
}
.content{
    margin-top: 100px;
    width: 50px;
    height: 50px;
    background-color: green;
}
小于等于父元素设定的margin值.jpg
2.大于父元素设定的margin值时
.content{
    margin-left: 50px;
    margin-top: 150px;
    width: 50px;
    height: 50px;
    background-color: green;
}
大于父元素设定的margin值.jpg

不但子元素执行margin-top,还要连带着父元素一起执行
这个现象是因为垂直方向的margin父子元素是结合到一起的
二者共同取最大的值,就好像父级的顶边不存在了
这个效果叫做margin塌陷

四、解决margin塌陷的办法 触发bfc

.wrapper{
    margin-left: 100px;
    margin-top: 150px;
    width: 100px;
    height: 100px;
    background-color: black;
    position:absolute;
}

针对性的 没影响的 选择触发父级的bfc方式 改变父级渲染规则以解决问题

.content{
    margin-left: 50px;
    margin-top: 100px;
    width: 50px;
    height: 50px;
    background-color: green;
}

五、margin合并bug

HTML

<span class="box1">123</span>
    <span class="box2">234</span>

CSS

.box1{
    background-color: red;
    margin-right: 100px;
}
.box2{
    background-color: green;
    margin-right: 100px;
}
两个盒子之间的距离累加不共用 区域不共用

HTML

<div class="demo1">1</div>
<div class="demo2">2</div>

CSS

.demo1{
    background-color: red;
    margin-bottom: 100px;
}
.demo2{
    background-color: green;
    marker-top: 200px;
}
两个兄弟结构垂直方向的margin合并100px+200px=200px

如果垂直方向的margin两个值均为正值:合并取大
eg:100px + 200px = 200px
两个值均为负值:合并取小
eg:(-20px) + (-30px) = -30px
两个值为一正一负:正负抵消
eg:(-20) + (30px) = 10px

margin合并.jpg

五、解决margin合并的办法 触发bfc

1.父级触发bfc
HTML

<div class="demo1">1</div>  
<div class="warpper">   
     <div class="demo2">2</div>
</div>

CSS

.warpper{
        display:inline-block;
}
.demo1{
    background-color: red;
    margin-bottom: 100px;
}
.demo2{
    background-color: green;
    marker-top: 200px;
}

2.或者把两个div都放在bfc环境里
HTML

<div class="wrapper">
    <div class="demo1">1</div>
    <div class="demo2">2</div>
</div>

最好不要以改动html的方式来修改bug
真实开发中选择不解决这个问题直接调节margin值即可
想要多少就把margin调成多少

上一篇 下一篇

猜你喜欢

热点阅读