天天看點

關于css中clear:both清除浮動防止父級元素高度坍塌的原理

不少小夥伴在防止高度坍塌時都會在浮動元素後面寫入一個div,再在裡面寫入clear:both屬性來清除浮動。那麼今天就在此探究一下clear:both的工作原理。

先說一下clear:both的作用 -----不允許周圍有浮動現象。

接下來直接上代碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>#box {
            height: 500px;
            width: 1300px;
            background-color: cornflowerblue;
            float: right;
        }
        
        .father {
            border: solid 1px pink;
        }
        
        .son1 {
            width: 200px;
            height: 200px;
            background-color: powderblue;
            float: left;
        }
        
        .son2 {
  
            clear: both;
            
        }</style>
</head>

<body>
    <div class="father">
        <div class="son1"></div>
        <div class="son2"></div>
        <div class="son3"></div>
    </div>
</body>

</html>