深入理解系列之 float

2025-08-19 23:21:10

float的设计初衷:

仅仅是为了实现文字环绕效果

float的感性认知:

包裹性:

收缩:元素应用了float后,宽度收缩,紧紧地包裹住内容(即元素的宽度收缩到元素内的内容的宽度大小

坚挺:原来没有高度,但元素应用了float后,元素的高度突然扩展到内容的高度大小

隔绝:元素应用了float后,盒子里面的内容发生了任何事情,都与盒子外的内容无关(BFC)

破坏性:

子元素应用了float后,父容器塌陷:父容器的高度变为0

tips: 具有包裹性(BFC特性)的其他属性:

display: inline-block/table-cell

position: absolute/fixed/sticky

overflow: hidden/scroll

具有破坏性的其他属性:

display: none

position: absolute/fixed/sticky

清除float对其他元素所带来的影响:

float元素底部插入一个带有 clear: both; 属性的元素

底部放置一个HTML block水平元素 -

CSS after(IE8+)伪元素底部生成 - .clearfix:after

父元素BFC化(IE8+)或 haslayout(IE6/7)

BFC/haslayout的通常声明

float: left/right

position: absolute/fixed

overflow: hidden/scroll(IE7+)

display: inline-block/table-cell(IE8+)

width/height/zoom: 1/...(IE6/7)

综上,IE8以上浏览器使用:

.clearfix:after {

content: '';

display: block;

height: 0;

overflow: hidden;

clear: both;

}

.clearfix {

*zoom: 1;

}

.clearfix:after {

content: '';

display: block;

height: 0;

overflow: hidden;

clear: both;

}

.clearfix {

*zoom: 1;

}

切记,.clearfix 只需应用在浮动元素的父级元素上 浮动的特性:

元素block块状化(砖头化)

破坏性造成的紧密排列特性(去空格化)

智能化自适应布局

很多其他内容

.container {

width: 600px;

margin: auto;

}

.left {

float: left;

margin-right: 20px;

}

.right {

display: table-cell;

*display: inline-block;

width: 2000px;

*width: auto;

}