【问题标题】:Center three buttons三个按钮居中
【发布时间】:2012-07-16 03:06:17
【问题描述】:

我在侧边栏中有以下布局:

<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 解决方案来完成此任务?

【问题讨论】:

  • 查看您正在应用的 CSS 会有所帮助。

标签: html css


【解决方案1】:

这是您需要的: 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;
}

【讨论】:

    【解决方案2】:

    解决方案是在 .center 元素上设置 text-align: center,在里面的 div 上设置 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;
    }
    

    注意:结束标签&lt;/div&gt;和下一个&lt;div&gt;的开始标签之间不能有任何空格

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2013-11-03
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2017-07-29
      相关资源
      最近更新 更多