如何使用"width auto"和"float"来对齐div?



我想在页面左侧有一个容器(带有一些文本),它可以根据可用空间进行调整,右侧后面有 2 个侧边栏(我使用的是 Wordpress)。(2 个侧边栏与 float 配合使用正常。所以我尝试在容器上width:auto

但它不会适应其余的可用空间(它占用所有页面宽度)。如果我将宽度设置为 70%,它适合索引页面上的空间,但如果我点击一篇文章,我只剩下 1 个侧边栏,所以文本和侧边栏之间有一个空白。

你知道怎么解决这个问题吗?

#container { /* the text */
    overflow:auto;
    width:auto;
    position:relative;
    float:left;
}
#primary { /* first sidebar */
    position:relative;
    border:1px solid red;
    float:right;
    width:250px;
}

#second { /* second sidebar */
    border:1px solid red;
    background:white;
    width:250px;
    height:auto;
    float:right;
    margin-left:15px;
}

谢谢


编辑:

假设我正在使用它而不是WordPress侧边栏:我仍然无法使其工作,有人可以用这个简单的代码看看吗? 有2个盒子:绿色的和红色的...

<!DOCTYPE>
<html>
    <head>
        <meta charset="UTF-8" />
    </head>
        <body>
            <div style="position:relative; width:700px; margin:0 auto;">
                <div style="width:auto; border:1px solid green;">i would like to have a container (with some text) on the left of the page, that adapts itself with the space available, and 2 sidebars following on the right (i'm using Wordpress). (The 2 sidebars work fine with float. ) So i tried width:auto on the container.
But it does not adapt itself with the rest of the space available (it takes all the page width). If i set the width to 70%, it fits the space on the index page, but if i click on an article, i only have 1 sidebar left, so there is a blank space between the text and the sidebar.</div>
<div style="width:20%; float:right; border:1px solid red;">blablabla</div>
            </div>
        </body>
</html>

width:auto 是默认值,因此除了 DIV 作为标准所做的工作外,它不会执行任何其他操作,即填充可用宽度,因为它是块级元素。当您浮动它时,这会发生变化,它将包装其内容,因此可以是任何宽度,直至最大宽度。

我认为您遇到的麻烦是混合百分比宽度和固定宽度。我可以看到您要做什么 - 有一个固定宽度的侧边栏(或两个)和页面的其余部分灵活。在基于表格的布局时代,做到这一点真的很容易,但我们不要去那里!

听起来您想要一个流畅的布局,但有 2 个固定的列。可能值得阅读这篇文章,看看是否有任何适合你正在尝试做的事情:http://coding.smashingmagazine.com/2009/06/02/fixed-vs-fluid-vs-elastic-layout-whats-the-right-one-for-you/

在父div 上使用 display:table。然后在子项上显示:表格单元格。它们将按照在表格中的方式对齐。

#container { /* the text */
    overflow:auto;
    width:auto;
    position:relative;
    // float:left;
    display: table-cell;
    vertical-align:top;
}
#primary { /* first sidebar */
    position:relative;
    border:1px solid red;
    // float:right;
    width:250px;
    vertical-align:top;
}

#second { /* second sidebar */
    border:1px solid red;
    background:white;
    width:250px;
    height:auto;
    // float:right;
    margin-left:15px;
    display: table-cell;
    vertical-align:top;
}

好的,我发现了:将文本放在末尾,使用溢出:隐藏和自动,然后浮动在右侧的小容器上,感谢您的回答。

最新更新