CSS布局(二)之多列布局

376 阅读2分钟

「这是我参与11月更文挑战的第七天,活动详情查看:2021最后一次更文挑战」。

往期推荐:

css布局之全屏布局

前言

多列布局

两列布局

  • 两列布局也是比较经典的一种布局,由左右两列组成。其中一列的宽度固定,另一列宽度自适应,两列的高度也是固定,并且相等的。
<div class="layout">
    <div class="layout-left"></div> 
    <div class="layout-right"></div> 
</div>

image.png

通过float/margin-legt实现

首先,给左边一列一个固定的宽度,高度,在通过float:left开启左浮动,再给右边一列一个以在列宽度的margin-left即可。

.layout {
  width: 920px;
  height: 880px;
  .layout-left {
    float: left;
    width: 300px;
    height: 100%;
    background-color: crimson;
  }
  .layout-right {
    margin-left: 100px;
    height: 100%;
    background-color: yellowgreen;
  }
}

通过flex实现。

使用flex的话,代码会非常的简洁,只需要左列固定宽度,右列声明flex:1;使其自适应就可以了。

.layout {
  display: flex;
  width: 920px;
  height: 880px;
  .layout-left {
    width: 300px;
    background-color: crimson;
  }
  .layout-right {
    flex: 1;
    background-color: yellowgreen;
  }
}

三列布局

三列布局呢,紧挨着的两列宽度固定,另一列宽度自适应,每个列的高度是固定并且相等的。接下让我带大家具体看看是怎么实现的。

<div class="layout">
  <div class="layout-left"></div>
  <div class="layout-middle"></div>
  <div class="layout-right"></div>
</div>

image.png

flex实现

和上面的同理,使用flex可以非常方便的写出来,只能万物皆可flex。

.layout {
  display: flex;
  width: 920px;
  height: 880px;
  .layout-left {
    width: 100px;
    background-color: crimson;
  }
  .layout-middle {
    width: 200px;
    background-color: gray;
  }
  .layout-right {
    flex: 1;
    background-color: yellowgreen;
  }
}

float,margin-left实现

当然通过,float和margin-left也可以实现,只是相对麻烦点,没有flex那么简洁。

.layout {
  width: 920px;
  height: 880px;
  .layout-left {
    float: left;
    width: 100px;
    height: 100%;
    background-color: crimson;
  }
  .layout-middle {
    float: left;
    width: 200px;
    height: 100%;
    background-color: gray;
  }
  .layout-right {
    height: 100%;
    margin-left: 300px;
    background-color: yellowgreen;
  }
}

好,今天就到这里了,今天努力的你依然是最棒的。加油,加油,你最棒!加油,加油,你最强!哦豁,Bye Bye!!!