定位方案
普通流
- 元素按照其在HTML中的先后位置自上而下布局
- 行内元素水平排列,直到当行被占满然后换行,块级元素则会被渲染为完整的一个新行
- 所有元素默认都是普通流定位
浮动
- 元素首先按照普通流的位置出现,然后根据浮动的方向尽可能的向左边或右边偏移
绝对定位
- 元素会整体脱离普通流,因此绝对定位元素不会对其兄弟元素造成影响
BFC属于普通流
BFC(Block Formatting Context)
- BFC可以理解为元素的一个属性,拥有BFC属性的元素可以看成是一个隔离的容器,容器内的元素不会影响容器外的布局
如何触发BFC(触发条件)
- 根元素(html)
- 浮动元素(元素的 float 不是 none)
- 绝对定位(元素的 position 为 absolute 或 fixed)
- display 为 inline-block、table-cell、table-caption、table、table-row、table-group、table-header-group、table-footer-group、inline-table、flow-root、flex 或 inline-flex、grid 或 inline-grid
- overflow 值不为 visible 的块元素
- contain 值为 layout、content 或 paint 的元素
- 多列容器(元素的 column-count 或 column-width 不为 auto,包括 column-count 为 1)
BFC作用
1、可以避免外边距重叠
上下外边距重叠
<body><div class="cube"></div><div class="cube"></div>
</body><style>.cube {width: 100px;height: 100px;background: blue;margin: 100px;}
</style>
上下外边距不重叠
<body><div class="container"><div class="cube"></div></div><div class="container"><div class="cube"></div></div>
</body><style>.container {overflow: hidden;}.cube {width: 100px;height: 100px;background: blue;margin: 100px;}
</style>
2、清除浮动
<body><div class="container"><div class="cube"></div></div>
</body><style>.container {border: 1px solid red;overflow: hidden;}.cube {width: 100px;height: 100px;background: blue;margin: 100px;float: left;}
</style>
3、阻止元素被浮动元素覆盖
<body><div class="floatDiv"></div><div class="normalDiv"></div>
</body><style>.floatDiv {width: 100px;height: 100px;background-color: blue;float: left;}.normalDiv {width: 200px;height: 200px;background-color: red;overflow: hidden;}
</style>