網頁常用佈局方式

兩列布局(左邊固定,右邊自適應)

html結構

<div class="box">
    <div class="left">左邊</div>
    <div class="right">右邊</div>
</div>

1.浮動

.left {
    width: 200px;
    float: left;
    background-color: green;
}

.right {
    background-color: blue;
    overflow: hidden;/*方法一*/
    margin-left: 200px;/*方法二*/
}
  1. inline-block佈局
.box {
    font-size: 0;/*解決空格對inline-block元素的影響*/
}

.left {
    background-color: green;
    display: inline-block;
    width: 200px;
    font-size: 16px;
}

.right {
    background-color: blue;
    display: inline-block;
    width: calc(100% - 200px);
    font-size: 16px;
}
  1. 絕對定位
.box {
    position: relative;
}

.left {
    position: absolute;
    width: 200px;
    background-color: green;
}

.right {
    background-color: blue;

    margin-left: 200px; /*方法一*/

    position: absolute;/*方法二*/
    left: 200px;/*方法二*/
    right: 0;/*方法二*/
}
  1. 表格佈局
.box {
    display: table;
    width: 100%;
}

.left {
    width: 200px;
    background-color: green;
    display: table-cell;
}

.right {
    background-color: blue;
}
  1. 彈性盒子佈局
.box {
    display: flex;
}

.left {
    width: 200px;
    background-color: green;
}

.right {
    flex: 1;
    background-color: blue;
}
  1. 網格佈局
.box {
    display: grid;
    grid-template-rows: auto;
    grid-template-columns: 200px auto;
}

.left {
    background-color: green;
}

.right {
    background-color: blue;
}

三列布局(左右固定,中間自適應)


在三列布局中,考慮瀏覽器性能及網速問題,應該把中間的主題部分優先顯示出來,然後在顯示兩邊的。在寫的時候把中間的標籤寫在兩邊的上面
兩列布局很多也適用於三列布局,此處只描述兩種最經典的。

  1. 聖盃佈局

html部分

<div class="parent">
    <div class="center">1</div>
    <div class="left">2</div>
    <div class="right">3</div>
</div>

css部分

.column {
    float: left;
    }
            
.left, .right{
    width: 200px;
    background-color: red;
}

.left {
    margin-left: -100%;
}

.right {
    margin-left: -200px;
}

.center {
    width: 100%;
    padding: 0 200px;
    box-sizing: border-box;
    background-color: green;
}

  1. 雙飛翼佈局

html部分

<div class="parent">
    <div class="box column">
        <div class="center">中間</div>
    </div>
    <div class="left column">左邊</div>
    <div class="right column">右邊</div>
</div>

css部分

.column {
    float: left;
}

.right, .left {
    width: 200px;
    background-color: red;
}

.box {
    width: 100%;
}

.left {
    margin-left: -100%;
}

.right {
    margin-left: -200px;
}

.center {
    margin: 0 200px;
    background: green;
}

等高佈局

  1. 內外邊距相消法(模擬等高)

HTML部分

<div class="container">
    <div class="box1">
        <p>中</p>
        <p>國</p>
    </div>
    <div class="box2">
        <p>中國</p>
    </div>
    <div class="box3">
        <p>中國</p>
    </div>
</div>

css部分

.container {
    overflow: hidden;
}

.box1, .box2, .box3 {
    float: left;
    margin-left: 20px;
    padding-bottom: 9999px;
    margin-bottom: -9999px;
    width: 300px;
    background: skyblue;
}

以下方法在橫向佈局中都有描述,不在細述

  1. 表格佈局
  2. 彈性盒子佈局
  3. 網格佈局
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章