首頁常見問題正文

前端清除浮動(dòng)的幾種方法

更新時(shí)間:2023-03-08 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  在前端開發(fā)中,浮動(dòng)是經(jīng)常用到的一種樣式技巧,但同時(shí)也會(huì)帶來一些問題,如高度塌陷(clearfix),不規(guī)則盒模型等。下面介紹幾種清除浮動(dòng)的方式,并提供詳細(xì)的代碼演示。

  1.父級(jí)div定義height

  父級(jí)div手動(dòng)定義height值,但如果子元素高度超出父元素,則會(huì)出現(xiàn)內(nèi)容溢出的情況。

<div style="background-color: #ccc; height: 200px;">
  <div style="float: left; width: 100px; height: 100px; background-color: red;"></div>
  <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div>
</div>

  2.使用clear:both

  在浮動(dòng)元素下方添加一個(gè)空div元素,利用clear:both清除浮動(dòng)。但這種方式會(huì)增加無意義的標(biāo)簽。

<div style="background-color: #ccc;">
  <div style="float: left; width: 100px; height: 100px; background-color: red;"></div>
  <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div>
  <div style="clear: both;"></div>
</div>

  3.使用overflow:auto

  父級(jí)div添加overflow:auto樣式,可以自動(dòng)清除子元素的浮動(dòng),但需要注意滾動(dòng)條的出現(xiàn)。

<div style="background-color: #ccc; overflow: auto;">
  <div style="float: left; width: 100px; height: 100px; background-color: red;"></div>
  <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div>
</div>

  4.使用偽元素::after

  在父級(jí)div中使用偽元素::after,利用clear:both清除浮動(dòng),但需要注意添加content屬性,否則在某些瀏覽器中可能不起作用。

<div style="background-color: #ccc; position: relative;">
  <div style="float: left; width: 100px; height: 100px; background-color: red;"></div>
  <div style="float: right; width: 100px; height: 150px; background-color: blue;"></div>
  <div style="clear: both;"></div>
  <div style="position: absolute; bottom: 0; left: 0; right: 0; height: 0; content: '';"></div>
</div>

  以上幾種方式都可以清除浮動(dòng),具體使用哪種方式取決于實(shí)際情況和需求。

分享到:
在線咨詢 我要報(bào)名
和我們在線交談!