【问题标题】:How can I vertically center text in a ul navigation-bar without these multiple CSS conflicts?在没有这些多个 CSS 冲突的情况下,如何在 ul 导航栏中垂直居中文本?
【发布时间】:2012-04-21 09:10:47
【问题描述】:

我已经做了一个功能性的 CSS 导航栏,除了一些丑陋的 CSS 副作用 --

我试图将每个列表块中的文本垂直居中,而vertical-align: middle 不起作用。相反,我使用padding-top: 13px,但这会呈现没有列表元素其余部分的background-color 的填充区域,并且链接的display: inline block 样式确实不扩展到填充地区要么! (a:hover 仅影响填充下方的区域)

那么如何在没有这些 CSS 问题的情况下将列表元素中的文本垂直居中?

这是相关的 CSS:

/* header section */
#header
{
    padding-left: 115px;
    margin-bottom: 10px;
}
    #main-menu
    {
        list-style-type: none;
    }
    #main-menu li
    {
        border: 1px solid black;
        text-align: center;
        padding-top: 13px;

        color: #666;
        font-family: "Lucida Console";
        font-variant: small-caps;
        letter-spacing: 2px;

        /* for  block layout */
            display: -moz-inline-box; /* for firefox */
            display: inline-block;

        width: 153px;
        height: 32px;
    }
    #main-menu a:link, a:visited
    {
        display: -moz-inline-box; /* for firefox */
        display: inline-block;

        width: 100%;
        height: 100%;
        background-color: #eee;
    }
    #main-menu a:hover, a:active
    {
        background-color: #bbb;
    }<br /><br />

...这里是相关的 HTML:

        <!-- header section -->
        <div id = "header">
            <ul id = "main-menu">
                <!-- no spaces between list elements when all on the same line! -->
                <li><a href = "home.html" title = "home">home</a></li><li><a href = "about.html" title = "about">about</a></li><li><a href = "cart.html" title = "shopping cart">cart</a></li><li><a href = "login.html" title = "log in">login</a></li><li><a href = "createAccount.html" title = "create a new account">sign up</a></li>
            </ul>

        </div> <!-- end of header section -->

【问题讨论】:

    标签: css center padding vertical-alignment navigationbar


    【解决方案1】:

    我改变的地方:

    • 将链接更改为显示为块元素。
    • 删除了 li 元素顶部的填充。
    • 将该填充高度添加到 li 元素的高度。
    • 将 line-height 设置为 li 元素的高度。
    • 一些格式

    http://jsfiddle.net/gtr053/7yrX7/

    【讨论】:

    • 啊!我曾尝试过margin-top,但由于边距会影响不起作用的外部(而不是内部)。摆脱填充,并添加line-height 是解决方案,谢谢。没有考虑同时拥有height 和line-height,您能详细说明一下吗?
    • 是的,基本上你根据需要设置元素的高度,然后将 line-height 设置为任何高度。不过,这只适用于一行文本(有一些超出您需求范围的例外情况)。
    【解决方案2】:

    尝试设置行高

    line-height: 13px;
    

    【讨论】:

      【解决方案3】:

      我什么都不懂,但我刚刚用过它,它可以工作

      进入通用样式的Quick CSS

      li {
          display:inline;
          padding: 0px 50px;
      }
      

      第一个 px 将菜单项向下,第二个将它们分开。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-10
        • 1970-01-01
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多