css清除浮動

文檔流:文檔流是文檔中可顯示對象在排列時所占用的位置。
浮動:使元素脫離文檔流,按照指定方向發(fā)生移動,遇到父級邊界或者相鄰的浮動元素停了下來。

浮動產(chǎn)生的影響

浮動與元素超出包含框的時候,包含框不會自動伸高來閉合浮動元素,叫做高度塌陷。
如下所示:.main 和 .side 不會撐高父元素 .wrap 的高度

//  css代碼
<style>
       .wrap { border: 2px solid gray ; width: 400px;}
       .main { float: left;width: 200px;height: 100px; background-color: pink;}
       .side { float: right;width: 150px;height: 100px;background-color: greenyellow;}
       .footer { width: 300px; height: 100px;  background-color: yellow; }
</style>

//  html代碼
<div class="wrap" id="float1">
    <h2>浮動</h2>
    <div class="main left">.main{float:left;}</div>
    <div class="side right">.side{float:right;}</div>
</div>
<div class="footer">.footer</div>

如何清除浮動

  • 使用clear : left|right|both|none;
  • 閉合浮動元素,減少浮動帶來的影響

使用clear屬性:

1.在浮動元素的后面添加<div style="clear:both;"></div>

<style>
    .wrap { border: 2px solid gray; width: 400px;}
    .main { float: left; width: 200px; height: 100px;background-color: pink;}
    .side { float: right;width: 150px; height: 100px; background-color: greenyellow;}
    .footer { width: 300px;height: 100px; background-color: yellow;}
</style>
<body>
<div class="wrap" id="float1">
    <h2>clear清除浮動</h2>
    <div class="main left">.main{float:left;}</div>
    <div class="side right">.side{float:right;}</div>
    <div style="clear:both;"></div>
</div>
<div class="footer">.footer</div>
2.在浮動元素的后面添加<br clear="all">

將上一個例子中的<div style="clear:both;"></div>替換為<br clear="all">

父元素設(shè)置dispaly:table

在父元素的css中加入display:table,

.wrap{
        border: 2px solid gray;
        width: 400px;
        height: 100px;
        display: table;
    }
父元素設(shè)置overflow: hidden;

在父元素的css中加入overflow: hidden

.wrap{
        border: 2px solid gray;
        width: 400px;
        height: 100px;
        overflow: hidden;
    }


上面的例子中 .main 和 .side 中的一部分內(nèi)容溢出被隱藏,修改的辦法就是將height: 100px;去掉,讓元素自己撐開父元素,或者是把height的值設(shè)大一點,讓元素不溢出就好了。

 .wrap {
        border: 2px solid gray;
        width: 400px;
        overflow: hidden;
    }


還可以設(shè)置overflow: auto;

添加:after偽元素

給父元素添加偽元素

     .wrap:after{
            content:".";
            display:block;
            height:0;
            visibility:hidden;
            clear:both;
      }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽?zāi)J的外補...
    _Yfling閱讀 14,154評論 1 92
  • 什么是CSS清除浮動? 在非IE瀏覽器(如Firefox)下,當容器的高度為auto,且容器的內(nèi)容中有浮動(flo...
    秦至閱讀 464評論 1 8
  • 1、什么是css清除浮動? 在非IE瀏覽器下,當容器的高度為auto,且容器的內(nèi)容中有浮動的元素,在這種情況下,容...
    IMike閱讀 286評論 0 1
  • 在CSS布局中float屬性經(jīng)常會被用到,但使用float屬性后會使其在普通流中脫離父容器,讓人很苦惱。 浮動帶來...
    wmsj100閱讀 921評論 0 1
  • 清除浮動一般有兩種思路:一、利用clear屬性,清除浮動二、使父容器形成BFC 一、利用clear屬性,清除浮動c...
    饑人谷_紫塵閱讀 4,836評論 2 11

友情鏈接更多精彩內(nèi)容