CSS float 和 overflow:控制文字环绕与盒子位置

文字行可以绕过 float,而其块盒仍可能延伸到浮动元素后面。用 display: flow-root 建立块格式化上下文(BFC),可以让整个盒子避开浮动。普通块上的 overflow: auto 也能建立 BFC。

区分文字环绕和盒子位置

默认情况下,行盒会避开浮动,在浮动下方可以恢复原宽度。块的背景和边框可延伸到浮动后方。建立 BFC 后,块的边框盒不会与外部浮动的外边距盒重叠。横向空间不足时,块可能下移。 CSS 2.2 · Floats

在一个文件中比较五种布局

将代码保存为 float-overflow.html 后打开。前三例给同一段文字采用默认布局、overflow: auto、display: flow-root。后两例对比父元素是否把内部浮动计入高度。每个 .case 都建立独立 BFC。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>在浮动旁建立独立布局</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    * { box-sizing: border-box; }
    h1 { font-size: 24px; }
    .case { display: flow-root; max-width: 500px; margin-bottom: 24px; }
    .outside { float: right; width: 100px; height: 120px; margin-left: 12px; background: #168a91; }
    .text { background: #edf3fa; border: 2px solid #6f88a4; padding: 10px; }
    .text p, .inside p { margin: 0; }
    .auto { overflow: auto; }
    .flow { display: flow-root; }
    .inside { padding: 8px; border: 2px solid #6f88a4; background: #edf3fa; }
    .inside .tile { float: left; width: 80px; height: 100px; margin-right: 12px; background: #168a91; }
  </style>
</head>
<body>
<h1>比较 float 和 overflow</h1>
<section class="case">
  <h2>默认布局</h2>
  <div class="outside" aria-hidden="true"></div>
  <div class="text">
    <p>文字绕过绿色盒子。观察边框和背景延伸到哪里。空间越窄,同一段文字可能需要更多行。</p>
  </div>
</section>
<section class="case">
  <h2>overflow: auto</h2>
  <div class="outside" aria-hidden="true"></div>
  <div class="text auto">
    <p>文字绕过绿色盒子。观察边框和背景延伸到哪里。空间越窄,同一段文字可能需要更多行。</p>
  </div>
</section>
<section class="case">
  <h2>display: flow-root</h2>
  <div class="outside" aria-hidden="true"></div>
  <div class="text flow">
    <p>文字绕过绿色盒子。观察边框和背景延伸到哪里。空间越窄,同一段文字可能需要更多行。</p>
  </div>
</section>
<section class="case">
  <h2>内部浮动:普通父元素</h2>
  <div class="inside">
    <div class="tile" aria-hidden="true"></div>
    <p>简短正文</p>
  </div>
</section>
<section class="case">
  <h2>内部浮动:flow-root 父元素</h2>
  <div class="inside flow">
    <div class="tile" aria-hidden="true"></div>
    <p>简短正文</p>
  </div>
</section>
</body>
</html>

第一例的蓝色边框延伸到绿色浮动块后方。后两例的整个文本盒会避开浮动。改变窗口宽度,同时比较蓝色边界和文字行。

让父元素的高度包含内部浮动

普通父元素包住短段落,色块可能超出下边框。flow-root 父元素会把色块计入自动高度。只移除最后一例的 flow 类,对比后再恢复。要让下一个元素移到浮动下方,应在该元素上设置 clear: both。 CSS Display · flow-root

选择 flow-root、overflow 或 clear

需要滚动溢出内容时使用 overflow: auto。hidden 可能裁掉阴影或菜单。clip 自身不会建立 BFC,替换 hidden 后布局可能改变。只需隔离布局时可用 flow-root。 CSS Overflow · overflow