css佈局 之 左側寬度固定,右側自適應兩欄佈局

佈局代碼如下,文章統一使用佈局

<body>
    <div class="wrapper">
      <div class="left">左側寬度固定</div>
      <div class="right">右側寬度自適應</div>
    </div>
</body>

方法一、

左側左浮動,右側margin-left

父容器使用overflow: hidden意在解決浮動之後高度塌陷的問題。
左側使用左浮動,右側設置margin-left固定距離即可

效果圖:
在這裏插入圖片描述

wrapper樣式:

.wrapper {
        height: 200px;
        width: 100%;
        background: aliceblue;
        overflow: hidden;
      }

左側div樣式右側div樣式

.left {
        width: 200px;
        height: 150px;
        background: yellowgreen;
        float: left;
      }
 .right {
        height: 150px;
        background: sienna;
        margin-left: 200px;
      }

方法二、

float + BFC方法

左側浮動,但是右側盒子通過overflow: auto;形成了BFC,因此右側盒子不會與浮動的元素重疊。

wrapper樣式:

.wrapper {
        height: 200px;
        width: 100%;
        background: aliceblue;
        overflow: hidden;
      }

左側div樣式右側div樣式

.left {
        width: 200px;
        height: 150px;
        background: yellowgreen;
        float: left;
      }
 .right {
        height: 150px;
        background: sienna;
        overflow: auto;
      }

效果圖:在這裏插入圖片描述

方法三、

左側絕對定位,右側margin-left

父容器使用 position: relative 是爲了給子元素一個參照
左側使用 position: absolutetop,left爲0 是爲了固定位置,右側仍然設置margin-left固定距離即可

效果圖:
在這裏插入圖片描述
wrapper樣式:

.wrapper {
        height: 200px;
        width: 100%;
        background: aliceblue;
        position: relative;
      }

左側div樣式右側div樣式

.left {
        width: 200px;
        height: 150px;
        background: yellowgreen;
        position: absolute;
        top: 0;
        left: 0;
      }
 .right {
        height: 150px;
        background: sienna;
        margin-left: 200px;
      }

缺點:

  • 使用了絕對定位,若是用在某個div中,需要更改父容器的position。
  • 沒有清除浮動的方法,若左側盒子高於右側盒子,就會超出父容器的高度。因此只能通過設置父容器的min-height來放置這種情況。

方法四、

flex彈性佈局

父容器設置 display: flex;讓子div成爲容器方便管理
左側固定寬度,右側自動填充剩餘空間

關於flex屬性,不瞭解的可藉此傳送門 → 彈性佈局 flex

效果圖:
在這裏插入圖片描述

wrapper樣式:

.wrapper {
        height: 200px;
        width: 100%;
        background: aliceblue;
        display: flex;
      }

左側div樣式右側div樣式

.left {
        width: 200px;
        height: 150px;
        background: yellowgreen;
        flex: 0 0 200px;
      }
 .right {
        height: 150px;
        background: sienna;
        flex: 1;
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章