CSS之两栏布局

139 阅读1分钟

说明 两栏布局是指页面中共两栏,左边固定,右边自适应的布局。 假设左边宽度固定为200px,右边自适应。

1. 浮动
<div class="container">
    <div class="left">left</div>
    <div class="right">right</div>
</div>
1.1 float + margin-left
  • 将左边元素设置向左浮动,并设置其宽度为200px
  • 将右边元素的margin-left设置为200px
    .left {
          float: left;
          width: 200px;
          height: 400px;
          background-color: skyblue;
    }

    .right {
          margin-left: 200px;
          height: 400px;
          background-color: pink;
    }
1.2 float + overflow: hidden
  • 将左边元素设置为向左浮动,宽度设置为200px
  • 将右边元素设置为overflow: hidden
     .left {
          float: left;
          width: 200px;
          height: 400px;
          background-color: skyblue;
     }

    .right {
          overflow:hidden;
          height: 400px;
          background-color: pink;
    }
2. 弹性布局
  • 设置右边元素放大比例(flex-grow)为1
     .container {
           display: flex;
     }
     
     .left {
          width: 200px;
          height: 400px;
          background-color: skyblue;
     }

    .right {
    	  flex-grow: 1;
          height: 400px;
          background-color: pink;
    }
3. 绝对定位
3.1 左边元素绝对定位
  • 将父元素设置为相对定位
  • 左边元素设置为绝对定位
  • 右边元素的margin-left设置为200px
    .container {
          position: relative;
    }
    
    .left {
          position: absolute;
          top: 0;
          left: 0;
          width: 200px;
          height: 400px;
          background-color: skyblue;
    }

    .right {
    	  padding-left:200px;
	  height: 400px;
	  background-color: pink;
    }
3.2 右边元素绝对定位
  • 将父元素设置为相对定位
  • 左边元素宽度设置为200px
  • 右边元素设置为绝对定位,left 设置为200,其它3个值设为0
    .con {
          position: relative;
    }
    
    .left {
          width: 200px;
          height: 400px;
          background-color: skyblue;
    }

    .right {
    	  position: absolute;
          top: 0;
          right: 0;
          height: 400px;
          left:200px;
          bottom: 0;
          background-color: pink;
    }
4. table-cell伪表格布局
    .con {
         display: table;
    }
    
    .left {
          display: table-cell;
          width: 200px;
          height: 400px;
          background-color: skyblue;
    }

   .right {
    	  display: table-cell;
          height: 400px;
          background-color: pink;
    }