2012-07-15 26 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>