1. 程式人生 > >清除浮動的方式

清除浮動的方式

1. 給父級定義height

.parent {
    background-color: red;
}
.float-left {
    width: 200px;
    height: 200px;
    float: left;
}
<div class="parent">
      <div class="float-left"></div>
</div>

2. 在結尾處新增空div,樣式設定為clear: both

.parent {
    background-color: red;
}
.float-left
{ width: 200px; height: 200px; float: left; }
<div class="parent">
    <div class="float-left"></div>
    <div style="clear: both"></div>
</div>

3. 父級定義偽類

.parent {
    background-color: red;
}
.float-left {
    width: 200px;
    height: 200px;
    float
: left; } .clearfloat:after { display: block; clear: both; content: ''; visibility: hidden; height: 0; zoom: 1; }
<div class="parent clearfloat">
    <div class="float-left"></div>
</div>

4. 把父級變成BFC

生成BFC的條件

  1. 根元素
  2. float的值不為none
  3. overflow的值不為visible
  4. display的值為inline-block、table-cell、table-caption
  5. position的值為absolute或fixed
.parent {
    background-color: red;
    float: left;
}
.parent {
    background-color: red;
    overflow: hidden;
}
.parent {
    background-color: red;
    display: table-cell;
}
.parent {
    background-color: red;
   	position: absolute;
}