如何在没有html表的情况下创建两列布局?

时间:2013-01-31 21:01:19

标签: javascript html css tablelayout

有几次我被告知我不应该使用表格进行布局设计,但是当我无法弄清楚如何做某事时,我总会发现自己会回到它们身上。

我需要创建一个两列布局。左列宽度为300px,右列占据页面宽度的其余部分。我无法弄清楚如何使用纯HTML正确地执行此操作,我甚至无法弄清楚如何使用表格来执行此操作。

为了让正确的列占据宽度的其余部分,似乎我需要用百分比指定左列的宽度,以便右列的宽度可以比左列的百分比小100%。但是我需要左列完全是300px。

我唯一能想到的就是使用JS在运行时计算右列的宽度。没有表格和/或没有Javascript我怎么能做到这一点?

4 个答案:

答案 0 :(得分:2)

Columns are pretty straight forward with floats。困难在于拥有父container clear the floated children

<子> HTML:
<div class="container">
  <div class="column column-a">
    ...
  </div>
  <div class="column column-b">
    ...
  </div>
</div>
<子> CSS:
.container {
  background-color: red;
  color: white;
  width: 520px;
  zoom: 1;
}
.container:before,
.container:after {
  content: '';
  display: table;
}
.container:after {
  clear: both;
}
.column-a {
  background-color: blue;
  float: left;
  width: 300px;
}
.column-b {
  background-color: green;
  float: right;
  width: 200px;
}

您应该注意,两列中较短的一列不会延伸到容器的底部。通常,两列的背景在包含元素上垂直重复。

如果您需要填充列,我通常会在每个div.inner元素中添加.column元素,但如果您想避免“divitis”,则只需添加:

.column {
    box-sizing: border-box;
    padding: 20px;
}

对于流体宽度的色谱柱,您所要做的就是确保宽度加起来为100%:

.column-a {
    width: 80%;
}
.column-b {
    width: 20%;
}

答案 1 :(得分:1)

<div>元素从根本上填充了容器的宽度或剩余的容量。因此,如果你有一个300px宽的div,那么旁边的div没有指定宽度,第二个div将填充容器的其余部分。

答案 2 :(得分:1)

在我们flexbox layout之前,我会使用绝对定位:

HTML:

<div id="container">
    <div id="left">left one</div>
    <div id="right">right one</div>
</div>

CSS:

#container {
    position: relative;
    height: 150px;
}

#left, #right {
    position: absolute;
    top: 0px; 
    bottom: 0px;
}

#left {
    left: 0px; 
    width: 300px;
    background: red;
}

#right {
    left: 300px; 
    right: 0px;    
    background: green;
}

jsfiddle

如果您希望布局适应内容而不是容器,则有其他选择。如果您的右栏有更多内容,您可以使用:

#container {
    position: relative;
}

#left {
    position: absolute;
    left: 0px; 
    width: 300px;
    top: 0px; bottom: 0px;
    background: red;
}

#right {
    margin-left : 300px; 
    background: green;
}

jsfiddle

如果您的左栏有更多内容,请使用:

#container {
    position: relative;
}

#left {
    width: 300px;
    background: red;
}

#right {
    position: absolute;
    left: 300px; 
    right: 0px;
    top: 0px; bottom: 0px;
    background: green;
}

jsfiddle

答案 3 :(得分:0)

将左列设置为300px,将右列设置为100%...完成。为了避免任何跨浏览器的怪异,请按照Matt Ball的链接... http://matthewjamestaylor.com/blog/ultimate-2-column-left-menu-pixels.htm。他正在使用一个我认为不必要的神秘的第二个包装纸,但宝贝步骤:)

一旦你进入包装器,要获得色谱柱高度=你需要将min-height设置为100%我相信。您可以调整overflow css属性来处理任何文本溢出。非常直接的东西,我记得有一段时间找到如何做相等的列,包装是关键。另外,不要使用JS,使用JS的人要么做更高级的事情,要么对html / css完全不熟悉。