CSS实现两列布局,一列固定宽度,一列宽度自适应方法

无论是左是右,反正就是一边宽度固定,一边宽度自适应。css

博客园的不少主题也是这样设计的,个人博客也是右侧固定宽度,左侧自适应屏幕的布局方式。html

html代码:浏览器

<div id="wrap">
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定宽度区</div>
  <div id="content" style="height:500px;background:#000;color:#fff;">自适应区</div>
</div>

实现方式方式有以下几种:ide

1.固定宽度区浮动,自适应区不设宽度而设置 margin

咱们以右侧宽度固定,左侧宽度自适应为例:布局

css代码:spa

#sidebar {
  float: right; width: 300px;
}
#content {
  margin-right: 300px;
}

实现效果图:设计

右侧一直固定不动,左侧根据屏幕的剩余大小自适应。code

但实际上这个方法是有局限性的,那就是html结构中sidebar必须在content以前才行htm

但我须要sidebar在content以后!由于个人content里面才是网页的主要内容,我不想主要内容反而排在次要内容后面。blog

那么上面讲解的第一种方法就无效了。

就须要下面的方法来实现。

2.float与margin配合使用

首先咱们调整一下html结构:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">
    <div class="contentInner">
       自适应区
    </div>
  </div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定宽度区</div>
</div>

css代码:

#content {
  margin-left: -300px; float: left; width: 100%;
}
#content .contentInner{
  margin-left:300px;
}
#sidebar {
  float: right; width: 300px;
}

这样实现,contentInner的实际宽度就是屏幕宽度-300px。

3.固定宽度区使用绝对定位,自适应区设置margin

html结构:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">我如今的结构是在前面</div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定宽度区</div>
</div>

css代码:

#wrap{
  position:relative;
}
#content {
  margin-right:300px;
}
#sidebar {
  position:absolute;
  width:300px;
  right:0;
  top:0;
}

4.使用display:table实现

html结构:

<div id="wrap">
  <div id="content" style="height:500px;background:#000;color:#fff;">我如今的结构是在前面</div>
  <div id="sidebar" style="height:500px;background:red;color:#fff;">固定宽度区</div>
</div>

css代码:

#wrap{
  display:table;
  width:100%;
}
#content {
  display:table-cell;
}
#sidebar {
 width:300px;
  display:table-cell;
}

固然最后一种方法在IE7以及如下浏览器不兼容,由于IE7设置display为table不识别。

相关文章
相关标签/搜索