簡體   English   中英

HTML元素不會擴展到父級li尺寸

[英]HTML a element doesn't expand to parent li dimensions

我有一個水平導航欄,並且我的a元素沒有擴展為父li元素的寬度和高度。

如何修復CSS,使a元素與外部/父li元素一樣寬和高?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
    <!--
        #navbar {
            width: 450px;
            height: 40px;
            background-color: RGB(112,112,112);
            list-style: none;
        }

        #navbar li {
            width: 112.5px;
            height: 40px;
            display: inline; 
            float: left;
        }

        #navbar li a {
            color: white;
            width: 112.5px;
            height: 40px;
        }

        #navbar a:link {
            background-color: red;
        }

        #navbar a:visited {
            background-color: purple;
        }

        #navbar a:active {
            background-color: green;
        }
        #navbar a:hover {
            background-color: blue;
        }
    -->
    </style>
</head>
<body>

    <ul id="navbar">
        <li><a href="">home</a></li>
        <li><a href="">contact us</a></li>
        <li><a href="">about us</a></li>
        <li><a href="">other</a></li>
    </ul>

</body>
</html>

通過使所有a元素display:block

但是,為什么,sdleihssirhc? 為什么?

因為<a>元素默認情況下是一個內聯元素,這意味着(在很多其他事情中)您不能給它指定寬度或高度。 如果嘗試,瀏覽器將忽略您。

使所有的a元素display: inline-block

它結合了兩全其美的優點-您可以將它們並排放置,而無需使用float ,並為它們提供任意widthheight 您甚至可以使用vertical-align來確定它應如何與周圍的文本對齊!

我已縮進其他行以幫助外觀。 如sdleihssirhc所述,必須將a元素設置為display:block 還要注意,通過在頂部添加一些填充(並從塊的總高度中減去),我們也可以實現一些垂直居中。


<style type="text/css">
<!--
#navbar {
    width: 450px;
    height: 40px;
    background-color: RGB(112,112,112);
    list-style: none;
        padding: 0;
}

#navbar li {
    width: 112.5px;
    height: 40px;
    display: inline; 
    float: left;
}

#navbar li a {
        display: block;
        float:left;
        padding-top: 6px;
        text-align: center;
    color: white;
    width: 112.5px;
    height: 34px;
}

#navbar a:link {
    background-color: red;
}

#navbar a:visited {
    background-color: purple;
}

#navbar a:active {
    background-color: green;
}
#navbar a:hover {
    background-color: blue;
}
-->
</style>

如下修改CSS:

#navbar li a {
...
    display: table;
    height: 100%;
    width: 100%;
...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM