• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

CSS实现两栏布局的方式

武飞扬头像
儒rs
帮助1

【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; 这样右边就触发了BFCBFC的区域不会与浮动元素发生重叠,所以两侧就不会发生重叠。
  • 对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;
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeiack
系列文章
更多 icon
同类精品
更多 icon
继续加载