css清除浮動定位造成的異常


清除浮動是為了解決高度塌陷的問題:內層有好幾個div有寬有高,並且選擇了浮動定位,但是外層的div卻並沒有設置寬高。在非IE瀏覽器(如Firefox)下,當容器的高度為auto,且容器的內容中有浮動(float為left或right)的元素,在這種情況下,容器的高度不能自動伸長以適應內容的高度,使得內容溢出到容器外面而影響(甚至破壞)布局的現象。這個現象叫浮動溢出,為了防止這個現象的出現而進行的CSS處理,就叫CSS清除浮動。

沒有清除浮動前:高度為0

清除浮動后:有了高度

 

常見解決方案:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    *{
        padding: 0;
        margin: 0;
        border: 0;
        outline: 0;
    }
    p{
        line-height: 150%;
    }
    /*清除浮動方法3 全局 for FF/chrome/opera/IE8== */
    :after {clear:both;content:'.';display:block;width: 0;height: 0;visibility:hidden;}  

    .test{
        
        background: rgb(164, 206, 188);
        margin: 0 auto;
        width: 150px;

        /*清除浮動方法2  clear:overflow*/
        /*height: auto;
        overflow: auto;
        zoom:1;*/
    }
    .div1{
        float:left; 
        width:50px;
        height:50px;
        text-align: center;
        line-height: 50px;
        border-bottom: 1px #ddd solid;
    }
</style>
<body>

    <div class="test">
        <div class="div1">1</div>
        <div class="div1">2</div>
        <div class="div1">3</div>
        <!-- 清除浮動方法1  clear:both -->
        <!-- <div style="clear:both;"></div> -->
    </div>

</body>
</html>

 

 

當然,你也可以直接給外層加個寬高 == 簡單粗暴又有效

或者,內層選擇html5的分列顯示,也是很好的方案

再或者,直接用一些框架的欄柵結構

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM