CSS系列 -- 清除浮动

444 阅读2分钟

场景

一个大盒子 Box,里面包含两个小盒子 box1、box2,想让 box1、box2 的高度来撑开 Box ,使得 Box 能做到 高度自适应(因为大盒子 Box 里面可能还有其他盒子 box3、box4、... 只是它们还未因为用户交互而被添加上去)。代码如下:

<div class="Box">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
.Box{
  background-color: gray;
  width: 100px;
}
.box1{
  background-color: yellow;
  width: 25px;
  height: 40px;
}
.box2{
  background-color: blue;
  width: 75px;
  height: 60px;
}

这里可以看到:Box 没有设置高度,但其包含的 box1 有高度 40px、box2 有高度 60px,所以其撑开的大盒子 Box 的高度为 40 +60 = 100px

image.png

如果大盒子 Box 里面有小盒子 box1 或 box2 或两者都因为需求被设为浮动,那么浮动元素内容的高是不可以撑起盒子的高

.Box{
  background-color: gray;
  width: 100px;
}
.box1{
  background-color: yellow;
  width: 25px;
  height: 40px;
  float: left;
}
.box2{
  background-color: blue;
  width: 75px;
  height: 60px;
  float: right;
}

image.png ( 只有 box1 浮动 ) image.png ( 只有 box2 浮动 ) image.png ( box1 、box2 都浮动 )

因此我们得出结论:

浮动产生原因:1. 大盒子没有设置高度;2. 内部元素设置浮动

浮动带来的问题:大盒子内部浮动元素内容的高不可以撑起盒子的高

所以我们需要清除浮动,这里介绍两种方式:

清除浮动

1. 父级元素设置 overflow: hidden

.Box{
  background-color: gray;
  width: 100px;
  overflow: hidden;
}

父级元素被里面的子级元素内容撑开,高度为 max ( box1 , box2 ) = 60 px

image.png

为什么加入overflow:hidden即可清除浮动呢?

那是因为overflow:hidden属性相当于是让父级紧贴内容,这样即可紧贴其对象内内容(包括使用float的div盒子),从而实现了清除浮动。

2. 在父级元素里面添加带 clear 属性的标签

<div class="Box">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="clear"></div> <!-- 添加此元素 -->
</div>
.clear {
  clear: both; /* 为该元素添加属性 clear: both; */
}

image.png

其他方式参考: