天天看點

使用float浮動後出現重疊問題:浮動元素與後面相鄰元素重疊解決辦法:結果:原理:

問題:浮動元素與後面相鄰元素重疊

原因:

使用float浮動後,浮動元素脫離文檔流,其他盒子會無視這個元素

如果浮動元素後面緊鄰的是普通塊級元素,浮動元素就會和文檔流發生重疊

代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 300px;
            height: 200px;
            background-color: green;
            float: left;
        }
    
        .box2 {
            width: 350px;
            height: 250px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
</body>
</html>
           

結果:

使用float浮動後出現重疊問題:浮動元素與後面相鄰元素重疊解決辦法:結果:原理:

解決辦法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 300px;
            height: 200px;
            background-color: green;
            float: left;
        }
    
        .box2 {
            width: 350px;
            height: 250px;
            background-color: red;
        }
        /*
        給浮動元素增加一個父元素,在其父元素上添加 display: flow-root屬性
        */
        .container{
           display: flow-root;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box1"></div>
    </div>
    <div class="box2"></div>
</body>
</html>
           

結果:

使用float浮動後出現重疊問題:浮動元素與後面相鄰元素重疊解決辦法:結果:原理:

原理:

  • 在父級塊中使用 display: flow-root 屬性可以建立無副作用的BFC
  • BFC 即 Block Formatting Contexts (塊級格式化上下文),具有 BFC 特性的元素可以看作是隔離了的獨立容器,容器裡面的元素不會在布局上影響到外面的元素
  • 是以給浮動元素的父級元素加上 display: flow-root 屬性,可以使浮動元素不影響BFC容器外元素的布局