HTML

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

基于 flex

  • 代码
	.main {
	    display: flex;
	}
	.left {
	    background-color: pink;
	    height: 200px;
	    flex-basis: 200px;
	}
	.right {
	    background-color: red;
	    height: 200px;
	    flex: 1;	
	}
  • 解释
  1. 左边设置flex-basis,是指定左边容器的基准值,相当于设置 width: 200px
  2. 右边设置flex: 1,等同于flex-grow: 1,表示有富裕空间时按权重分配富裕空间,而此时仅有右边占有权重,因此拥有全部富裕空间

基于 float

  • 代码
	.left {
	    background-color: pink;
	    height: 200px;
	    width: 200px;
	    float: left;
	}
	.right {
	    background-color: red;
	    height: 200px;
	    margin-left: 200px;
	}
  • 解释
  1. 左边设置浮动,目的是让左边容器脱离正常文档流,可以与右边容器处在同一行
  2. 右边设置margin-left: 200px,是为了避免与左边发生重叠

基于绝对定位

  • 代码
	.main {
	    position: relative
	}
	.left {
	    background-color: pink;
	    height: 200px;
	    width: 200px;
	    position: absolute;
	    top: 0;
	    left: 0;
	}
	.right {
	    background-color: red;
	    height: 200px;
	    margin-left: 200px;
	}
  • 解释
  1. 父元素设置position: relative,是为了给子元素提供定位参考,这里是左边的容器
  2. 左边设置position: absolute,是为了以父元素为基准定位,同时也是为了脱离正常文档流,可以于右边处于同一行,通过top、left,定位在了左上角
  3. 右边设置margin-left: 200px,是为了避免与左边发生重叠

基于绝对定位2

	.main {
	    position: relative;
	    height: 200px;
	}
	.left {
	    width: 200px;
	    height: 200px;
	    background: tomato;
	}
	.right {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 200px;
		background: gold;
	}
  • 解释
  1. 父元素设置为relative为子元素提供定位参考
  2. 右边的容器使用absolute以父元素定位,并脱离普通文档流,再通过right:0,使得元素的宽度可以占满剩余空间

基于 calc()

  • 代码
	.left {
	    background-color: pink;
	    height: 200px;
	    width: 200px;
	    float: left;
	}
	.right {
	    background-color: red;
	    height: 200px;
	    float: left;
	    width: calc(100% - 200px);
	}
  • 解释
  1. 左右都浮动是为了让他们都在一行
  2. 右边的宽度利用 calc 函数,直接将剩余的空间计算出来

效果

两栏布局——左边固定宽度、右边自适应_前端