CSS两栏布局实现

2,391 阅读3分钟

  CSS中两栏布局、三栏布局都是很常见也很经典的布局方案。作为开发者,对这些布局方案必须了然于心,开发起来才能得心应手。笔者现在也是处于学习阶段,所以通过查阅资料和自己总结,在这篇文章中介绍常见的两栏布局实现方案,一共四种,下一篇文章将介绍经典三栏布局方案。

  所谓两栏布局,指的是页面中一共两栏,左边固定宽度,右边宽度自适应;或者右边固定宽度,左边宽度自适应的布局方案。实现原理是类似的。我们以固定部分的宽度200px为例。以下,除第一种外,我们都以左边固定,右边自适应为例。            

实现一(1):浮动+margin-left实现左边固定,右边自适应

HTML代码如下:

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

CSS代码如下:

.parent{
    height: 600px;;
  } 
  .left{
    float: left;
    height: 600px;
    width: 200px;
    background: tomato;
  }
  .right{
    width: auto;
    margin-left: 200px;
    height: 600px;
    background: gold;
  }
实现一(2):浮动+margin-right实现右边固定,左边自适应

HTML代码如下:

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

CSS实现如下:

.parent{
    height: 600px;;
  } 
  .left{
    height: 600px;
    width: auto;
    margin-right: 200px;
    background: tomato;
  }
  .right{
    float: right;
    width: 200px;
    height: 600px;
    background: gold;
  }

  这里之所以要把两种都写出来,是因为有一个细节,想特别说明一下。观察它们的HTML结构,不难发现,设置了哪个div浮动,就要把那个div的DOM结构放在另一个前面,不然不会出来我们想要的效果。有兴趣的小伙伴可以自己试一下。

实现二:利用flex

HTML代码如下:

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

CSS代码如下:

.parent{
    display: flex;
   height: 600px;;
 } 
 .left{
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 200px;
   background: tomato;
 }
 .right{
   flex: auto;
   background: gold;
 }
实现三:绝对定位+margin-left。将父级元素设置相对定位。左边元素设置为 absolute 定位,并且宽度设置为 200px。将右边元素的 margin-left 的值设置为 200px。

HTML代码如下:

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

CSS代码如下:

.parent{
    position: relative;
   height: 600px;;
 } 
 .left{
   position: absolute;
   width: 200px;
   height: 600px;
   background: tomato;
 }
 .right{
   height: 600px;
   margin-left: 200px;
   background: gold;
 }
实现四:还是利用绝对定位的方式,将父级元素设置为相对定位。左边元素宽度设置为 200px,右边元素设置为绝对定位,左边定位为 200px,其余方向定位为 0。

HTML代码如下:

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

CSS代码如下:

.parent{
     position: relative;
    height: 600px;;
  } 
  .left{
    width: 200px;
    height: 600px;
    background: tomato;
  }
  .right{
    height: 600px;
    position: absolute;
    top: 0;
    left: 200px;
    right: 0;
    bottom: 0;
    background: gold;
  }

有任何问题,欢迎在评论区交流哦!