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

时间:2014-10-27 22:32:26

标签: html css alignment

令人尴尬的是,我无法让一个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(或内联),我可以将它们放在同一条线上。 .menublock似乎不喜欢在此展示中居中,margin: 0 auto;不起作用。我正在弄乱.menublock display:table,但不想留在同一行。

3 个答案:

答案 0 :(得分:6)

也许这太容易了,所以你甚至都没有尝试过,但是我在测试文件中解决了这个问题:只需交换<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>

答案 1 :(得分: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;  
}

答案 2 :(得分:0)

Merlin's和James&#39;解决方案运作良好他们都取得了同样的结果。

我刚发现的另一个解决方案是将text-align: center;添加到.container类。事实证明内联元素响应text-align(尽管以这种方式考虑div似乎很奇怪。)

相关问题