两列div布局,左侧流体和右侧固定柱

Sil*_*ght 50 html css fluid-layout

我想使用DIV进行两列布局,其中右列的固定宽度为200px,左侧列将占用剩余的所有空间.

如果您使用表格,这很容易:

<table width="100%">
  <tr>
    <td>Column 1</td>
    <td width="200">Column 2 (always 200px)</td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

但DIV怎么样?有可能做到这一点吗?如果是,那怎么样?

Sal*_*n A 88

以下示例是源排序的,即第1列出现在HTML源代码的第2列之前.列是左侧还是右侧是由CSS控制的:

固定权利

#wrapper {
  margin-right: 200px;
}
#content {
  float: left;
  width: 100%;
  background-color: #CCF;
}
#sidebar {
  float: right;
  width: 200px;
  margin-right: -200px;
  background-color: #FFA;
}
#cleared {
  clear: both;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  <div id="content">Column 1 (fluid)</div>
  <div id="sidebar">Column 2 (fixed)</div>
  <div id="cleared"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

固定左

#wrapper {
  margin-left: 200px;
}
#content {
  float: right;
  width: 100%;
  background-color: #CCF;
}
#sidebar {
  float: left;
  width: 200px;
  margin-left: -200px;
  background-color: #FFA;
}
#cleared {
  clear: both;
}
Run Code Online (Sandbox Code Playgroud)
<div id="wrapper">
  <div id="content">Column 1 (fluid)</div>
  <div id="sidebar">Column 2 (fixed)</div>
  <div id="cleared"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

替代解决方案是使用display:table-cell ; 这导致高度相等的列.


lee*_*ade 12

这是一个解决方案(它有一些怪癖,但如果你注意到它们,请告诉我,并且它们是一个问题):

<div>
    <div style="width:200px;float:left;display:inline-block;">
        Hello world
    </div>
    <div style="margin-left:200px;">
        Hello world
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 不用担心,这是一个正确的解决方案;) - 在检查之后:`display:inline-block`在上面的代码中不是必需的,但`display:inline`可能对IE6及以下版本有用,因为双边距错误 - *if*it's遇到 (2认同)

cla*_*uzy 6

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>
Run Code Online (Sandbox Code Playgroud)

上面应该可以工作,你可以把代码放在包装器中,如果你想给它宽度和中心它,overflow:hidden在没有宽度的列上是使它包含的关键,垂直,如不包围侧列(可左或右)

如果需要它,可能还需要zoom:1在#content div上设置IE6


Hus*_*ein 5

CSS Solutuion

#left{
    float:right;
    width:200px;
    height:500px;
    background:red;   
}

#right{
    margin-right: 200px;
    height:500px;
    background:blue;
}
Run Code Online (Sandbox Code Playgroud)

查看http://jsfiddle.net/NP4vb/3/上的工作示例

jQuery解决方案

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);
Run Code Online (Sandbox Code Playgroud)

查看工作示例http://jsfiddle.net/NP4vb/