【CSS】实现两栏布局的方式

【CSS】实现两栏布局的方式

一般两栏布局指的是左边一栏宽度固定,右边一栏宽度自适应。两栏布局的具体实现有以下几种方式:

① 利用浮动

    利用浮动,将左边元素宽度设置为200px,并且设置向左浮动。 将右边元素的margin-left设置为200px,宽度设置为auto(默认为auto,撑满整个父元素)。
.container {
          
   
  height: 100px;
}
.left {
          
   
  float: left;
  width: 200px;
  height: 100px;
  background: tomato;
}
.right {
          
   
  margin-left: 200px;
  width: auto;
  height: 100px;
  background: gold;
}

以下给出html模板:

<div class="container">
     <div class="left"></div>
     <div class="right"></div>
</div>

② 浮动 + BFC

    利用浮动,左侧元素设置固定大小,并左浮动。 右侧元素设置overflow: hidden; 这样右边就触发了BFC,BFC的区域不会与浮动元素发生重叠,所以两侧就不会发生重叠。 对BFC不了解的,可以参考
.left{
          
   
	 float: left;
     width: 100px;
     height: 200px;
     background: tomato;
 }
 .right{
          
   
     overflow: hidden;//触发BFC
     height: 300px;
     background: gold;
 }

③ 利用flex布局

利用flex布局,将左边元素设置为固定宽度200px,将右边的元素设置为flex:1。

.container {
          
   
  display: flex;
  height: 100px;
}
.left {
          
   
  width: 200px;
  background: tomato;
}
.right {
          
   
  flex: 1;
  background: gold;
}

的布局采取了类似的策略:

④ 利用绝对定位

    利用绝对定位,将父级元素设置为相对定位。 左边元素设置为absolute定位,并且固定宽度设置为200px,left值设置为0。 将右边元素的left值设置为左边固定宽度200px,right值设置为0。
.container {
          
   
    position: relative;
    box-sizing: border-box;
}
.left {
          
   
    position: absolute;
    left: 0;
    width: 200px;
    height: 200px;
    background: tomato;
}
.right {
          
   
    position: absolute;
    left: 200px;
    right: 0;
    height: 300px;
    background: gold;
}

⑤ 利用网格布局

使用Grid网格布局实现两栏布局的要点在于列数为2,且首列的宽度根据需要自行设置,第二列使用片段"fr"属性进行自适应即可。 行数不需要指定,每行会根据内容高度进行自适应缩放。

    现在给类名为"container"的盒子添加"display: grid"属性,使该盒子成为容器。 再给该容器添加"grid-template-columns: 100px 1fr"属性,表示第一列宽度始终为100px,第二列的宽度为剩余的所有空间。 此时可以看到整个容器的高度因为首列的内容被撑开了,并且右边内容区实现了自适应。
.container {
          
   
    display: grid;
    grid-template-columns: 100px 1fr;
    box-sizing: border-box;
}
.left {
          
   
    width: 100px;
    height: 200px;
    background: tomato;
}
.right {
          
   
    height: 300px;
    background: gold;
}
经验分享 程序员 微信小程序 职场和发展