兩欄佈局、三欄佈局

兩欄佈局

float + bfc

利用浮動和浮動元素對塊級元素不可見(浮動元素會蓋住非浮動的塊級元素),然後觸發被覆蓋的塊級元素的 bfc,這樣可以是右邊藍色的部分不被左邊紅色部分覆蓋,而是剛好銜接。如果不觸發 bfc 可以設置右邊的的 margin-left=左邊的寬度,但是不能實現右邊的元素自適應。
在這裏插入圖片描述

<div>
    <p></p>
    <p></p>
</div>
p {
	height: 20px;
	margin: 0px; // 去除p標籤默認 margin
}
p:nth-child(1) {
	background-color: red;
	float: left;
	width: 300px;
}
p:nth-child(2) {
	background-color: blue;
	overflow: hidden; // 觸發 bfc
}

flex

設置爲 flex 之後,子元素都變成 inline-block,給左側設置固定寬度,flex-grow 默認爲 0,右側設置 flex-grow:1,表示有剩餘空間,就全部是它的。
在這裏插入圖片描述

		div {
            display: flex;
            height: 100px;
        }
        p {
            height: 20px;
            margin: 0px;
        }
        p:nth-child(1) {
            background-color: cornsilk;
            width: 300px;
        }
        p:nth-child(2) {
            background-color: darkorchid;
            flex-grow: 1;
        }

三欄佈局

float + bfc

在這裏插入圖片描述
這裏有個 bug,如果使用這種方式,那麼我們必須把第二個元素當做浮動在最右邊的元素。

		div {
            height: 100px;
        }
        p {
            height: 20px;
            margin: 0px;
        }
        p:nth-child(1) {
            background-color: red;
            width: 300px;
            float: left;
        }
        p:nth-child(2) {
            background-color: darkturquoise;
            float: right;
            width: 300px;
        }
        p:nth-child(3) {
            background-color: blue;
            overflow: hidden;
        }

flex

在這裏插入圖片描述

		div {
            height: 100px;
            display: flex;
        }
        p {
            height: 20px;
            margin: 0px;
        }
        p:nth-child(1) {
            background-color: red;
            width: 300px;
        }
        p:nth-child(2) {
            background-color: darkturquoise;
            flex-grow: 1;
        }
        p:nth-child(3) {
            background-color: blue;
            width: 300px;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章