略微偏离中心的按钮

时间:2015-05-21 14:31:05

标签: html css

enter image description here

我需要这些按钮在容器内水平居中。如你所见,它们向左浮动。那是因为我有一个浮动:左;属于他们。

然而,当我移除浮子:左;属性并应用text-align:center;到容器,这就是发生的事情......

enter image description here

几乎居中,但并不完全。这笔交易是什么?谢谢! :)

容器的CSS:

    #navbar {
    background: #303030;
    width: 100%;
    box-sizing: border-box;
    text-align: center;
}

每个按钮的CSS:

        a.button {
        width: 16.3%;
        background: #4d4d4d;
        height: 50px;
        display: inline-block;
        text-decoration: none;
        color: #fff;
        text-align: center;
        max-width: 250px;
        padding-top: 12px;      
        box-sizing: border-box;
        font-size: 145%;
        transition-property: background, z-index, font-size, color;
        transition-duration: 0.35s;         
    }

相关的HTML

    <div id ="navbar">
<a href="https://www.answers.legal" class="button"><i class="fa fa-home"></i> HOME</a>
<a href="https://www.answers.legal/questions" class="button"><i class="fa fa-question"></i> Q&A</a>
<a href="https://www.answers.legal/forums" class="button"><i class="fa fa-comment"></i> FORUMS</a>
<a href="https://www.answers.legal/contact" class="button"><i class="fa fa-phone"></i> CONTACT</a>
<a href="https://www.answers.legal/support" class="button"><i class="fa fa-life-ring"></i> SUPPORT</a>
<a href="https://www.answers.legal/about" class="button"><i class="fa fa-info-circle"></i> ABOUT</a>
</div>
</div>

1 个答案:

答案 0 :(得分:2)

错位可能是由于每个链接之间的空格字符。使用display: inline-block;时这是一个常见问题。您可以使用几种方法删除。

方法1: 设置为负letter-spacing。这取决于font-family和font-size,因此请尝试几个不同的值。

#navbar {
    letter-spacing: -4px; 
}

a.button {
    letter-spacing: normal;
}

方法2: 删除链接之间的所有空格/换行符。这当然会使代码变得难以理解。

<a href="https://www.answers.legal" class="button"><i class="fa fa-home"></i> HOME</a><a href="https://www.answers.legal/questions" class="button"><i class="fa fa-question"></i> Q&A</a><a href="https://www.answers.legal/forums" class="button"><i class="fa fa-comment"></i> FORUMS</a><a href="https://www.answers.legal/contact" class="button"><i class="fa fa-phone"></i> CONTACT</a><a href="https://www.answers.legal/support" class="button"><i class="fa fa-life-ring"></i> SUPPORT</a><a href="https://www.answers.legal/about" class="button"><i class="fa fa-info-circle"></i> ABOUT</a>

方法3: 除了最后一个,忽略所有链接的结束</a>。这仍然是有效的HTML。如果<a>元素后跟另一个<a>,它将自动关闭。

<a href="https://www.answers.legal" class="button"><i class="fa fa-home"></i> HOME
<a href="https://www.answers.legal/questions" class="button"><i class="fa fa-question"></i> Q&A
<a href="https://www.answers.legal/forums" class="button"><i class="fa fa-comment"></i> FORUMS
<a href="https://www.answers.legal/contact" class="button"><i class="fa fa-phone"></i> CONTACT
<a href="https://www.answers.legal/support" class="button"><i class="fa fa-life-ring"></i> SUPPORT
<a href="https://www.answers.legal/about" class="button"><i class="fa fa-info-circle"></i> ABOUT</a>