两列布局

左固定,右自适应

首先是html代码:

<div class="parent">
        <div class="left">固定</div>
        <div class="right">自适应</div>
</div>
方法:直接只用float就可以,不知道以下方法加上的好处?
方法一:使用float+margin-left实现
.left{
background-color: pink;
height: 300px;
width: 200px;
float: left;
}
.right{
background-color: green;
height: 300px;
margin-left:200px;
}

左侧布局左浮动,定宽,右侧布局margin-left:左侧宽度;

方法二:使用float+overflow:auto/hidden
.left{
background-color: pink;
height: 300px;
width: 200px;
float: left;
}
.right{
background-color: green;
height: 300px;
overflow:auto;
/*overflow:hidden;也可以*/
}
方法三:使用flex
.parent{
  display: flex;
}
.left{
background-color: pink;
height: 300px;
flex: 0 0 200px;
}
.right{
background-color: green;
height: 300px;
flex:1 1 auto;
}

使用flex布局,左侧flex:0 0 200px,不扩大不缩小,固定宽度,右侧自适应扩大缩小。
左侧固定200px,右侧自适应:


image.png

右固定,左自适应

还是html代码:

  <div class="parent">    
       <div class="left">固定区</div>
        <div class="right">自适应区</div>
    </div>
方法:使用float:right就行了,不知道加上以下方法的好处?
方法一:使用float+margin-right:
 .left{
        width:200px;
        height: 300px;
        background-color: pink;
        float: right;
     }

  .right{
        height: 300px;
        background-color: green;
        margin-right: 200px;
     }

html代码中,固定放在左边的,但在布局上是在右边,所以要更改html代码,此方法就无效了。


image.png

修改html代码,让代码和布局一致:

<div class="parent">
        <div class="free">自适应区</div>
        <div class="box">固定区</div>
    </div>
方法二:使用absolute+top+right:
.parent{
    position: relative;
}
.box{
 background-color: green;
 width: 200px;
 height: 300px;
 position: absolute; 
 right: 0; 
 top: 0;

}
.free{
    margin-right: 200px;
    height: 300px;
    background-color: pink;
}

就达到这个效果了,代码和布局一致:


image.png

但是,使用绝对定位对后面元素的布局不是很好,所以该方法得改进。

方法三:使用float+margin:

html代码:

 <div class="parent">
        <div class="freeBox">
            <div class="free">自适应区</div>
         </div>
        <div class="box">固定区</div>
    </div>

css代码:

.freeBox{
    float: left;
    margin-left: -200px;
    width: 100%;
    height: 300px;
    background-color: green;
}

.free{
    margin-left: 200px;
}

.box{
    float: right;
    width: 200px;
    height: 300px;
    background-color: pink;
}

图片显示:


image.png
方法四:标准方法display:table

没有那么麻烦的方法:
html代码:

 <div class="parent">
       <div class="freeBox">自适应区域</div>
       <div class="rightBox">固定区域</div>
</div>

css代码:

.parent{
    display: table;
    width: 100%
}
.freeBox{
    display: table-cell;
    height: 300px;
    background-color: yellow;
}
.rightBox{
    display: table-cell;
    width: 200px;
    background-color: pink;
    height: 300px;
}

父元素设置display为table,宽度100%,子元素都是table-cell,右边部分设置宽度,左边就自适应了。
图片显示:


image.png

部分参考:http://jo2.org/css-auto-adapt-width/
height和background-color都是为了显示便于看,不为关键代码。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容