0

有人多次告诉我,我不应该使用表格进行布局设计,但是当我不知道如何做某事时,我经常发现自己会回到表格中。

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

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

我唯一能想到的就是在运行时用 JS 计算右列的宽度。任何想法如何在没有表格和/或没有 Javascript 的情况下完成此任务?

4

4 回答 4

2

带有 floats 的列非常简单。困难在于让父容器清除浮动的子容器

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%;
}
于 2013-01-31T22:20:05.287 回答
1

<div>元素从根本上填充其容器的宽度,或者它的剩余部分。因此,如果您有一个 300px 宽的 div,然后在它旁边有一个没有指定宽度的 div,则第二个 div 将填充容器的其余部分。

于 2013-01-31T21:05:15.890 回答
1

在我们有flexbox 布局之前,我会使用绝对定位:

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

于 2013-01-31T21:07:06.007 回答
0

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

一旦进入包装器,要获得列高 = 我相信您需要将 min-height 设置为 100%。您可以调整溢出 css 属性以处理任何文本溢出。非常直接的东西,我记得我花了很长时间寻找如何做相等的列,包装器是关键。另外,不要为此使用 JS,使用 JS 的人要么在做更高级的事情,要么对 html/css 完全陌生。

于 2013-01-31T21:10:15.727 回答