浮动 float
float left/right、文字环绕、clear 清除浮动、clearfix 技巧
浮动 float
float 让元素"浮起来"——原本用于图文混排,现在多用于传统布局。
学完本章你将: 掌握 float left/right、文字环绕、clear 清除浮动。
基本用法
css
.float-left { float: left; } /* 左浮动 */
.float-right { float: right; } /* 右浮动 */
.none { float: none; } /* 不浮动(默认) */
文字环绕
html
<img src="photo.jpg" style="float: left; margin-right: 15px;">
<p>文字会环绕在图片右侧……</p>
清除浮动
css
/* clear:不让元素旁边有浮动元素 */
.clear-left { clear: left; }
.clear-right { clear: right; }
.clear-both { clear: both; } /* 清除两侧浮动 */
clearfix 技巧
css
/* 父元素包含浮动子元素时——高度塌陷 */
.clearfix::after {
content: "";
display: table;
clear: both;
}
html
<div class="clearfix">
<div style="float: left;">左</div>
<div style="float: right;">右</div>
</div>
<!-- clearfix 让父元素正确包裹浮动的子元素 -->
💡 现代布局优先用 Flexbox/Grid,float 仅在图文混排时使用。