BFC布局解析

BFC (Block Formatting Context)即块格式化上下文

一.布局规则

   1.BFC内盒子依次垂直排列

   2.BFC内两个盒子之间的垂直距离由margin属性决定。属于同一个BFC内的两个相邻盒子margin会发生重叠

   3.BFC内的区域不会与浮动的盒子重叠

   4.BFC就是页面上的一个隔离容器,容器里的子元素不会影响容器外面的元素

二.创建BFC

   1.每个根元素都是BFC布局

    2.给元素设置float属性(left,right)

    3.给元素设置position属性(absolute,fixed)

    4.给父元素设置overfolw除visible属性

    4.给元素设置display属性(inline-block,table-cell,table-caption)

三.BFC的应用

   1.防止margin重叠

    

<style>
    .a{
        height: 100px;
        width: 100px;
        margin: 50px;
        background: pink;
    }
</style>
<body>
    <div class="a"></div>
    <div class="a"></div>
</body>

//两个div的margin并不是两个盒子margin相加的100px,而是重叠了50px,如果两个盒子的margin不一样,非BFC布局的情况下,最终的margin以margin值大的盒子为准


解决方式
<style>
    .a{
        height: 100px;
        width: 100px;
        margin: 50px;
        background: pink;
    }
.container{
  overflow:auto
} </style> <body>
  <div class="container">   <div class="a"></div>
</div> <div class="a"></div> </body>
//根据创建BFC的第四个方法给父元素添加overflow:auto属性,此时两个盒子的margin即为两者的margin相加100px
 

2.清除内部浮动

   给父元素设置overflow:auto或display:inline-block属性

猜你喜欢

转载自www.cnblogs.com/myspecialzone/p/12209333.html
BFC
今日推荐