CSS 清除浮动

HTML+CSS 中浮动样式

在编写 html 样式的时候难免会遇到元素使用浮动属性导致元素样式坍塌的情况,我们使用清除浮动来解决样式坍塌问题。
注意

  1. 浮动元素不会覆盖文字内容
  2. 浮动元素不会覆盖图片内容
  3. 浮动元素不会覆盖表单元素(输入框、单选按钮、复选框、按钮、下拉选择框等等)

坍塌示例

坍塌示例

解决坍塌问题后示例效果

解决示例效果1

在这里给出基本结构代码,以下有几种示例方法能够解决浮动导致的布局坍塌

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        float: left;
      }

      .box:nth-child(1) {
        width: 20%;
        background-color: red;
        height: 50px;
      }

      .box:nth-child(2) {
        width: 30%;
        background-color: pink;
        height: 80px;
      }

      .box:nth-child(3) {
        width: 50%;
        background-color: blue;
        height: 100px;
      }
      .other {
        background: gray;
        width: 100%;
        height: 100px;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
    <div class="other"></div>
  </body>
</html>

1.给父元素添加 overflow 属性

.outer {
  overflow: auto;
}

2. 给浮动元素后面的元素添加 clear 属性

.clearfix {
  clear: both;
}
<body>
  <div class="outer">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="other clearfix"></div>
</body>

3.给父元素添加固定的高度

如果子元素的高度大于父元素所设定的高度这种方式会导致内容溢出,
可以设置 overflow:hidden;隐藏溢出的内容

.outer {
  height: 100px;
  /* overflow:hidden; */
}

4. :after 伪元素

.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1; /* IE 6 7*/
}
<body>
  <div class="outer  clearfix">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="other"></div>
</body>

5.使用 before 和 after 双伪元素清除浮动

.clearfix:before,
.clearfix:after {
  content: "";
  display: block;
}
.clearfix:after {
  clear: both;
}
.clearfix {
  *zoom: 1; /* IE 6 7*/
}
<body>
  <div class="outer clearfix">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
  <div class="other"></div>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值