CSS 清除浮動



清除浮動是一種技術,用於確保容器正確包含其內的浮動元素(例如影像)。它透過向容器新增一個空元素來防止佈局問題,該元素清除左右兩側的浮動。

左浮動
右浮動
後續內容

清除浮動的工作原理?

要理解清除浮動的工作原理,首先您需要了解 **float** 屬性和浮動元素。在 CSS 中,浮動元素是從正常文件流中移除並放置在其包含塊的左側或右側的元素。例如,有時影像元素會放置在容器元素的右側,文字會環繞它。

由於浮動元素已從正常的文件流中移除,父容器可能會摺疊並且無法包含浮動的子元素。因此,使用清除浮動技術可確保父元素正確地環繞浮動元素。以下是清除浮動的基本 CSS 程式碼

.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

以上語法遵循以下規則。

  • content: "" 用於生成偽元素。
  • display: table 使偽元素成為塊級元素,並確保它佔據父元素的全部寬度。
  • clear: both 清除兩側(左側和右側)的浮動。

清除浮動有助於防止容器摺疊、高度不一致、內容重疊、對齊不一致等問題。

CSS 清除浮動的示例

以下 HTML 程式碼展示瞭如何使用清除浮動來防止容器摺疊。

示例

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            border: 3px solid;
            padding: 5px;
        }
        
        img {
            float: right;
            width: 150px;
        }
        
        .clearfix::after {
            content: "";
            clear: both;
            display: table;
        }
    </style>
</head>

<body>
    <h2>Without Clearfix</h2>
    <div>
        <img src="/css/images/css.png">
        This image is floated to the right. As the image is 
        taller than the container, it overflows to outside.
    </div>

    <h2 style="clear:right">With Clearfix</h2>
    <div class="clearfix">
        <img src="/css/images/css.png" >
        Here we added clearfix class to the containing element, 
        to fix this problem.
    </div>

</body>
</html>

使用 overflow 屬性的 CSS 清除浮動

我們還可以使用 CSS 中的 **overflow** 屬性實現與清除浮動類似的功能。`overflow: auto;` 將使容器延伸以適應所有內部元素。

不建議使用此方法。只要能夠控制頁邊距和內邊距(否則可能會看到捲軸),`overflow:auto` 清除浮動效果很好。

示例

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            border: 3px solid;
            padding: 5px;
        }
        
        img {
            float: right;
            width: 150px;
            border: 1px solid;
        }
        
        .clearfix {
            overflow: auto;
        }
    </style>
</head>

<body>
    <h2>Without Clearfix</h2>
    <div>
        <img src="/css/images/css.png">
        This image is floated to the right. As the image is 
        taller than the container, it overflows to outside.
    </div>

    <h2 style="clear:right">With Clearfix</h2>
    <div class="clearfix">
        <img src="/css/images/css.png" >
        Here we added clearfix class to the containing element, 
        to fix this problem.
    </div>
</body>

</html>
廣告