两个并排的 div,一个居中,另一个右浮动。

4

尴尬的是,我无法将一个任意长度的 div 居中,也无法将另一个任意长度的 div 向右浮动。因此,我有一个带有菜单按钮的容器,这些按钮居中,右侧有一个链接,指向用户控制面板。它应该长这样:

 ----------------------------------------------------------------------------
|                       |----Menu Items----|                |--ControlPanel--|
 ----------------------------------------------------------------------------

我知道,这个问题可能已经被问过几次了,但我已经反复搜索了一遍又一遍,它们似乎都依赖于百分比或固定宽度。

我有一个容器

.container {
    height: 50px;   
    width: 100%;
    padding: 10px 10px;
}
.menublock {
    width: 200px;
    margin: 0 auto;
    padding: 0;
}
.controllinks {
    float:right;    
}

HTML的结构如下所示:

<div class="container">
    <div class="menublock">
        <span class="menuitem">Streams</span>
        <span class="menuitem">Profile</span>
        <span class="menuitem">Friends</span>
    </div>
    <div class="controllinks">
        A link the users control panel
    </div>
</div>

通过将 menublock 和 controllinks 改为 display:inline-block(或 inline),我可以轻松地使它们在同一行上。但似乎 .menublock 不喜欢在此布局中居中,margin:0 auto; 无效。我尝试使用 .menublock display:table 进行调整,但它不想保持在同一行。
3个回答

8
也许这太简单了,所以你甚至没有尝试过,但这个方法可以修复我的测试文件中的问题:只需交换<div class="controllinks"><div class="menublock">的顺序即可:
<div class="container">
    <div class="controllinks">
        A link the users control panel
    </div>
    <div class="menublock">
        <span class="menuitem">Streams</span>
        <span class="menuitem">Profile</span>
        <span class="menuitem">Friends</span>
    </div>
</div>

这个很好用。说实话,我从来没有尝试过那样做。谢谢! - DWB
1
在使用浮动时,请始终记住,只有在浮动元素之后的元素才会围绕它浮动。通常情况下,它之前的元素不会浮动。 - Merlin Denker

3

一个简单的解决方案是使用绝对定位。

.container {
    height: 50px;   
    width: 100%;
    padding: 10px 10px;
    /*this makes the child divs relative to the parent*/
    position:relative;
}
.menublock {
    width: 200px;
    margin: 0 auto;
    padding: 0;
}
.controllinks {
    /*this puts the controllinks on the right. 
    Be warned, that if the page is too small, controllinks can no overlap on menublock. 
    This can be fixed with media queries.*/
    position:absolute;
    right:0px;  
}

这肯定有效,我想在这种情况下避免使用绝对值。请查看我的另一条评论,了解我发现的另一种解决方案。 - DWB
@DeepakBhalla 是的,这很容易理解。在这种情况下,他的解决方案似乎更简单/更好。 - James G.

1

梅林和詹姆斯的解决方案都很好,它们都实现了相同的结果。

我刚刚发现的另一种解决方案是在 .container 类中添加 text-align: center;。结果发现内联元素响应 text-align(尽管这样考虑 divs 看起来有些奇怪)。


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