2012-07-15 63 views
0

我在側邊欄以下佈局:中心三個按鈕

<div class="sidebar"> 
    <div class="center"> 
     <div>button one</div> 
     <div>button two</div> 
     <div>button three</div> 
    </div> 
</div> 

我能夠通過設置center寬度= 100%和按鈕divs爲33%至居中這三個按鈕。

.sidebar { 
    width: 300px 
} 
.center { 
    width: 100%; 
    background: red; 
    margin: 0 auto; 
} 
.center div { 
    width: 33%; 
} 

不過,我想佈局,以保持居中時,我只有兩個按鈕:

<div class="sidebar"> 
    <div class="center"> 
     <div>button one</div> 
     <div>button two</div> 
    </div> 
</div> 

所以這兩個按鈕是在中心(即縮進兩個按鈕16.66%從右邊緣和左邊緣,在沒有第三個按鈕的情況下)。

我該如何用純粹的css解決方案來實現?

+3

開始標記這將有助於看到你應用CSS之間的空白。 – j08691 2012-07-15 18:53:18

回答

3

這是你所需要的: http://jsfiddle.net/HFaTW/

HTML:

<div class="sidebar"> 
    <div class="center"> 
     <div>button one</div> 
     <div>button two</div> 
     <div>button three</div> 
    </div> 
</div> 

CSS:

.sidebar{ 
    width:400px; 
} 

.center{ 
    background-color:#f9f9f9; 
    text-align:center; 
} 

.center div{ 
    display:inline-block; 
    margin-left:5px; 
    margin-right:5px; 
    color:#FFF; 
    background-color:darkgray; 
} 
+0

爲我工作,不能相信我從來不知道這一點。 – Doidgey 2012-08-17 10:28:07

0

該解決方案是設置裏面的div text-align: center的.center元素和display: inline-block - 演示http://dabblet.com/gist/3118171

的HTML CSS &(這兩種情況下):

<div class="sidebar"> 
    <div class="center"> 
     <div>button one</div><div>button two</div><div>button three</div> 
    </div> 
</div> 

<div class="sidebar"> 
    <div class="center"> 
     <div>button one</div><div>button two</div> 
    </div> 
</div> 

.sidebar { 
    width: 40%; 
} 
.center { 
    width: 100%; 
    text-align: center; 
} 
.center div { 
    width: 33.33%; 
    display: inline-block; 
} 

注意:你不應該有什麼樣的結束標記</div>和下一<div>