CSS 浮动(Float)及其应用

发布于:2025-05-19 ⋅ 阅读:(20) ⋅ 点赞:(0)

1. 什么是浮动(Float)?

浮动元素会脱离正常的文档流(Document Flow),并向左或向右移动,直到碰到父元素的边缘或另一个浮动元素。

基本语法

.float-left {
  float: left;
}

.float-right {
  float: right;
}

.no-float {
  float: none; /* 默认值 */
}

2. 浮动的常见应用场景

(1) 文字环绕图片

<div class="container">
  <img src="example.jpg" class="float-left" alt="示例图片">
  <p>这里是环绕的文字内容……</p>
</div>

效果:图片浮动在左侧,文字自动环绕在其右侧。 在这里插入图片描述

(2) 多列布局(传统方式)

在 Flexbox 和 Grid 流行之前,浮动是创建多列布局的主要方式。

.father {
            border: black solid;

            width: 1250px;
            margin: 20px;
            background-color: #f5f5f5;
        }

        .left,
        .right {
            float: left;
            margin-left: 10px;
        }

        .left {
            height: 410px;
            width: 200px;
            background-color: black;
        }

        .right {
            height: 410px;
            width: 950px;
            background-color: blue;
        }

        .grandson {
            height: 188px;
            width: 200px;
            background-color: yellow;
            float: left;
            margin-left: 30px;
            margin-top: 10px;
        }

在这里插入图片描述
最外黑框线父元素father为文档流,其所有孩子都为浮动流,黑色区块left为一列,蓝色区块right为一列。蓝色区块内又有黄色浮动流grandson。

3. 浮动带来的问题及解决方案

(1) 父元素高度塌陷(Collapsing Parent)

问题:当子元素浮动后,父元素无法自动计算高度,导致布局错乱。

<body>
    <div class="father">
        <div class="left"></div>
        <div class="right">
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
            <div class="grandson"></div>
        </div>
        <div class="clear"></div>
    </div>
    <div class="no">this is not a content</div>
</body>

显示为:
发现父元素高度发生塌陷,后一位文档流顶了上来。
在这里插入图片描述

解决方案

  • 方法1:使用 clearfix 技巧(推荐)
    .clearfix:after {
              content: "";
              display: block;
              height: 0;
              clear: both;
              visibility: hidden;
          }
    
          .clearfix {
              /* IE6、7 专有 */
              *zoom: 1;
          }
    
    <div class="father clearfix">
    
    成功解决:
    在这里插入图片描述
  • 方法2:使用额外标签
============style============
.clear{
clear:both;
}
=============body============
<div class="clear"></div>>

(2) 浮动元素之间的间隙问题

问题:多个浮动元素之间可能出现意外的空白间隙。
原因:HTML 换行符被解析为空格,或 margin 未正确设置。
解决方案

  • 移除 HTML 换行(不推荐)
    <div class="float-left"></div><div class="float-left"></div>
    
  • 使用 margin 调整间距
    .float-item {
      float: left;
      margin-right: 10px;
    }
    
  • 改用 Flexbox 或 Grid(现代布局方案)

网站公告

今日签到

点亮在社区的每一天
去签到