float和clear

簡介

float CSS屬性指定一個元素應沿其容器的左側或右側放置,容許文本和內聯元素環繞它。該元素從網頁的正常流動中移除,儘管仍然保持部分的流動性。css

浮動元素是float值不爲none的元素html

可能值:佈局

  • left: 代表元素必須浮動在其所在的塊容器左側
  • right: 代表元素必須浮動在其所在的塊容器右側
  • none:元素不進行浮動

特色

1. 塊佈局

float意味着使用塊佈局。flex

float會將所應用元素的display值修改成block。即若是元素自己的display爲inline、inline-block、inline-table、table-row、table-row-group、table-column、table-column-group、table-cell等,那麼變爲浮動元素後該display值會被修改成block。3d

float對flex、inline-flex不起做用。若是元素的display爲flex、inline-flex,則不會被修改,由於float對它們不起做用。code

2. 浮動定位

當一個元素浮動以後,它會被移除正常的文檔流,而後向左或向右平移,一直平移直到碰到所處容器的邊框,或者碰到另一個浮動的元素htm

3. 受所在容器高度影響

正常的浮動定位效果的實現須要知足前提條件:浮動元素的高度比其所在容器的高度小blog

若是浮動元素的高度比其所在容器的高度大。那麼容器也不會被該浮動元素撐大,因此容器下面的兄弟元素也會跑到浮動元素的一側。若是不想要浮動元素也浮動在容器接下來的兄弟元素的一側,那麼須要對容器的該兄弟元素進行 清除浮動(clear屬性)。文檔

實踐

1. 浮動元素高度比所在容器高度小

代碼:get

<div class="container">
    <div class="item float1">
      float1
    </div>
    <div class="item float2">
      float2
    </div>
    <div class="item float3">
      float3
    </div>
    哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈
    哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈呵呵哈哈哈哈哈哈哈
  </div>
.container{
    background: yellow;
  }
  .item {
    width: 100px;
    height: 100px;
  }
  .float1 {
    background: red;
    float: left;
  }
  .float2 {
    background: blue;

    float: left;
  }
  .float3 {
    background: orange;

    float:right;
  }

效果:

2. 浮動元素比所在容器高度大

代碼:

<div class="container">
    <div class="item float1">
      float1
    </div>
    <div class="item float2">
      float2
    </div>
    <div class="item float3">
      float3
    </div>

    哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
  </div>
  <div class="otherbox">
    啦啦啦
  </div>
.container{
    background: yellow;
  }
  .item {
    width: 100px;
    height: 100px;
  }
  .float1 {
    background: red;
    float: left;
  }
  .float2 {
    background: blue;

    float: left;
  }
  .float3 {
    background: orange;

    float:right;
  }
  .otherbox {
    background: green;
  }

效果:

3. 當浮動元素比所在容器高度大時,消除對容器後面的元素的影響(清除浮動)

代碼:

在2.的基礎上,給.otherbox的樣式改成:

.otherbox {
  background: green;
  clear: both;
}

效果:

若是僅僅只clear一邊的浮動元素:

.container{
    background: yellow;
  }
  .item {
    width: 100px;
    height: 100px;
  }
  .float1 {
    background: red;
    float: left;
  }
  .float2 {
    background: blue;

    float: left;
  }
  .float3 {
    background: orange;
    height: 200px; /*爲了看清清楚左右浮動的區別,將float3高度改成200px*/
    float:right; 
  }
  .otherbox {
    background: green;
    clear: left;
  }

效果:

clear:right效果同理。

參考資料

https://developer.mozilla.org/zh-CN/docs/Web/CSS/clear

https://developer.mozilla.org/zh-CN/docs/CSS/float

相關文章
相關標籤/搜索