2014-10-27 24 views
1

尷尬,我在浮於右麻煩使一個DIV(任意長度)爲中心和一個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;不起作用。我正在搞.menublockdisplay:table但那不想留在同一行。

回答

5

也許是太容易了,所以你甚至沒有嘗試,但這個定格在我的測試文件的東西:只是交換的<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> 
+0

這工作得很好。坦率地說,我從來沒有嘗試過。謝謝! – Deepak 2014-10-27 22:45:00

+0

使用float時,請始終記住只有在浮動元素之後浮動的元素浮動。以前的那些通常不會。 – 2014-10-27 22:47:42

2

一個簡單的解決方案是使用絕對定位。

.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; 
} 
+0

這肯定工作,我想避免在這種情況下,使用絕對的。看到我對我發現的另一個解決方案的其他評論 – Deepak 2014-10-27 22:51:51

+0

@DeepakBhalla是的,這是可以理解的。在這種情況下,他的解決方案似乎更容易/更好。 – 2014-10-27 22:53:30

0

兩個梅林的和詹姆斯的解決方案運作良好他們都取得了相同的結果。

另一種解決方案我剛剛發現被添加text-align: center;.container類。事實證明,內聯元素響應文本對齊(儘管用這種方式來思考divs似乎很奇怪)。

相關問題