教程 css tutorial

float 与 clear

CSS 中,float 用于将元素从正常文档流中取出,向左或向右浮动;clear 用于控制元素不与浮动元素重叠,常用于清除浮动影响。

1. float 属性

  • float: left; 元素向左浮动。
  • float: right; 元素向右浮动。
  • float: none; 取消浮动,默认值。

浮动元素会脱离正常文档流,后续内容会环绕浮动元素。

css
float: left;

2. clear 属性

用来防止元素与之前的浮动元素重叠,清除浮动。

  • clear: left; 不允许左侧有浮动元素。
  • clear: right; 不允许右侧有浮动元素。
  • clear: both; 不允许左右两侧有浮动元素。
css
clear: both;

3. 清除浮动的重要性

浮动元素脱离文档流,父容器高度可能塌陷,使用 clear 或其他方法(如 clearfix)修复。

float 与 clear 示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>float 与 clear 示例</title> <style> .container { border: 1px solid #333; padding: 10px; margin-bottom: 20px; overflow: hidden; /* 清除浮动另一种方法 */ }

.float-left {
  float: left;
  width: 100px;
  height: 100px;
  background-color: #64b5f6;
  margin-right: 10px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.float-right {
  float: right;
  width: 100px;
  height: 100px;
  background-color: #4db6ac;
  color: white;
  line-height: 100px;
  text-align: center;
}

.clear-both {
  clear: both;
  background-color: #ffcc80;
  padding: 10px;
  text-align: center;
}

</style> </head>

<body> <div class="container"> <div class="float-left">浮动左</div> <div class="float-right">浮动右</div> <p>这段文字会围绕浮动元素排列。</p> <div class="clear-both">清除浮动,开始新布局</div> <p>清除浮动后,这段文字不会和上面的浮动元素重叠。</p> </div> </body>

</html>