2013-07-10 31 views
0

我想在位於中間的其他div的右側添加一個div。正如圖所示:在其他居中的div旁邊添加div

enter image description here

我有這個網站至今:

<div id= "top-menu-wrapper"> 
    <div id="top-menu">  
    </div> 
    <div id="social"> 
    </div> 
</div> 

的CSS:

#header #top-menu { 
    display   : inline-block; 
    width    : 764px; 
    height   : 55px; 
    margin   : auto; 
} 

#header #social { 
    display   : inline-block; 
    width    : 100px; 
    height   : 55px; 
    margin-left  : 25px; 

} 

#header #top-menu-wrapper { 
    display   : block; 
    text-align  : center; 
    margin-bottom  : 25px; 
} 
+0

相同寬度的僞它爲我,我剛添加的顏色的div所以你可以看到它。 (http://jsfiddle.net/nbatothemax/G7uC9/)可能是問題是你有一個'#header' ID作爲每個這些容器的父代,當你沒有給所有的頭容器時他們。另外,如果你的元素有ID,你不需要使用父選擇器來找到它們,因爲你可以立即得到它們。 –

回答

1

由於您的寬度是固定的,只計算左偏移的每個div,並將其作爲左邊距而不使用中央對齊。

或者,如果你的容器是流體,與中心的

(top container width - central div width)/2)寬度(表示在合適的剩餘空間)右浮動子容器內部的問題DIV

你可能會做如果使用JavaScript窗口調整大小偵聽器重新計算其在每個調整大小事件上的位置,它看起來是最好的。 (儘管你只想使用CSS,但我建議JS獲得最佳結果)

0

由於您使用內嵌塊顯示您的方框,因此父項可能有:text-align:center;,第二個方塊的負邊距爲自己的寬度,拉中間的第一個盒子。

http://codepen.io/gcyrillus/pen/ADsEx

背景顏色被用來示出其中框站立和標尺被添加到可視地檢查水平中心。

#top-menu { 
    display   : inline-block; 
    width    : 764px; 
    height   : 55px; 
    background  : green; 
} 

#social { 
    display   : inline-block; 
    width    : 100px; 
    height   : 55px; 
    margin-right  : -100px; 
    background  : yellow; 
} 

#top-menu-wrapper { 
    text-align  : center; 
    min-width   : 990px; 
    background  : purple; 
} 
div { 
    vertical-align : top; 
    padding   : 5px 0; 
} 
.ruler { 
    width    : 50%; 
    background  : red; 
    margin   : 5px 0 ; 
} 

這樣,你不介意父母的寬度,除非你想讓他們2總是在一行上。如果是這樣,那麼可以應用最小寬度:足夠寬。

另一種解決方案是增加的boxe 2. http://codepen.io/gcyrillus/pen/hipBl

body { 
    padding   : 2em; 
    margin   : 0; 
} 
#top-menu { 
    display   : inline-block; 
    width    : 764px; 
    height   : 55px; 
    background  : green; 
} 

#social, #top-menu-wrapper:before { 
    display   : inline-block; 
    width    : 100px; 
    height   : 55px; 
    background  : yellow; 
} 
#top-menu-wrapper:before { 
    content   : ''; 
    height   : 0; 
} 
#top-menu-wrapper { 
    text-align  : center; 
    min-width   : 990px; 
    background  : purple; 
} 
div { 
    vertical-align : top; 
    padding   : 5px 0; 
} 
.ruler { 
    width    : 50%; 
    background  : red; 
    margin   : 5px 0 ; 
}