2列布局(左列固定宽度,右列自适应宽度并清除浮动)

12

我需要帮助,因为我已经试了很长时间来解决这个问题。我需要:

我有一个两列布局,左边的列固定宽度为220px,右边的列宽度是流体的。

代码如下:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title>Fluid</title>
    <style type="text/css" media="screen">
        html, body { background: #ccc; }
        .wrap      { margin: 20px; padding: 20px; background: #fff; }
        .main      { margin-left: 220px; width: auto }
        .sidebar   { width: 200px; float: left; }
        .main,
        .sidebar   { background: #eee; min-height: 100px; }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sidebar">This is the static sidebar</div>
        <div class="main">This is the main, and fluid div</div>
    </div>
</body>
</html>

完全没有问题。当我在右列使用CSS语法clear: both时,所有内容都会被移到左列下面。这是正确的行为,没有任何问题。

但我真的需要在右列中使用clear:both,使其保持在右列的上下文中(完全不受左列的影响,并且不会移动到左列下面)

是否有简单的方法来保留页面设计的基本浮动概念?

更新:请查看此链接以了解我的意思,因为我的描述可能有点混淆。 链接:http://jsfiddle.net/k4L5K/1/


演示:http://jsfiddle.net/a4xyV/ - Jared Farrish
3个回答

25

这是您修改后的CSS:

html, body {
    background: #ccc;
}

.wrap {
    margin: 20px;
    padding: 20px;
    padding-right:240px;
    background: #fff;
    overflow:hidden;
}

.main {
    margin: 0 -220px 0 auto;
    width: 100%;
    float:right;
}

.sidebar {
    width: 200px;
    float: left;
    height: 200px;
}

.main, .sidebar {
    background: #eee; min-height: 100px;
}

.clear { clear:both; }
span { background: yellow }

基本上我所做的是改变了你的布局方式,使.main div在右侧浮动。为此,我们需要添加两个东西:

  1. .wrap div的padding为240px,并且
  2. .main div的右侧margin为-220px,以正确对齐页面流体部分。

因为我们已将.main div向右浮动,所以clear:both;现在只会影响.main div内部的内容,正如您希望的那样。

您可以在这里看到演示:http://jsfiddle.net/6d2qF/1/


这就是我一直在寻找的。谢谢!;) - Ondrej

0

这个问题很老了,但是我最近找到了另一个解决方案。

我们只需要做两件事:

  1. .main div 添加 overflow: auto;
  2. 确保包装器通过将 .wrap div 添加 overflow: hidden; 或者将 .clear div 添加为 .wrap 元素的最后一个子元素来保留文档流

这里是更新后的 fiddle:http://jsfiddle.net/k4L5K/89/


-2

试试这个:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title>Fluid</title>
    <style type="text/css" media="screen">
        html, body { background: #ccc; }
        .wrap      { margin: 20px; padding: 20px; background: #fff; }
        .main      { margin-left: 220px; width: auto }
        .sidebar   { width: 200px; }
        .main,
        .sidebar   { background: #eee; min-height: 100px; float: left; }
        .clear {clear:both;}
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sidebar">This is the static sidebar</div>
        <div class="main">This is the main, and fluid div</div>
        <div class="clear"></div>
    </div>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接