如何让<ul>在其所在的内容区域内均匀分布?</ul>

时间:2010-08-17 16:34:04

标签: html css html-lists

我有一个List,我正在使用它作为标签列表:

<div id="SearchForm">
    <ul class="TabControl">
        <li>
            <a href="/search/Funds">Funds (60)</a>
        </li>
        <li>
            <a href="/search/Companies">Companies (4)</a>
        </li>
        <li>
            <a href="/search/Groups">Groups (1)</a>
        </li>
        <li>
            <a href="/search/Categories">Categories (0)</a>
        </li>
        <li>
            <a href="/search/Categories">Identifiers (60)</a>
        </li>
    </ul>
</div>

其中CSS的定义如下:

#SearchForm ul {
    list-style: none;
    padding:0;
    margin: 15px 0 5px 0;
}

#SearchForm li {
    display: inline;
    background-color: #F6E9D8;
    margin: 12px 6px 0 0;
    padding: 6px 0 6px 0;   
}

#SearchForm li a {
    padding: 0 20px;
}

此列表仅占用页面上可用宽度的大约90%,其中页面中的其他所有内容占据宽度的100%,因为它们以div格式排列。可用于它们的空间在客户提供的元素中定义

 width: 62.1em

基本上我需要的是让标签均匀分布,以便它们填充可用的整个宽度,文本/链接在每个标签的中间对齐?我有办法做到这一点吗?

1 个答案:

答案 0 :(得分:5)

但当然。我把a demo here放在了一起。 CSS如下所示,并附有说明:

#SearchForm {
    /* Set width of parent div */
    width: 62.1em;   
}

#SearchForm ul {
    /* Make ul take 100% of its parent's width */
    width: 100%;

    list-style: none;
    padding: 0;
    margin: 15px 0 5px 0;
}

#SearchForm li {
    /* Float the li's left and give them 20% width (20% * 5 = 100%) */
    float: left;
    width: 20%;

    /* Make sure no horizontal padding/margin is applied.  Since we've set an 
       explicit width on the li, horizontal padding/margins would add to this, 
       making the element greater than 20% width and causing float drop */        
    margin: 12px 0 0 0;
    padding: 6px 0;   
}

#SearchForm li a {
    /* Set the nested links to display block and align their text center */
    display: block;
    text-align: center;

    /* Here we can safely apply horizontal padding/margins because we haven't
       explicitly set a width on the element */
    margin: 0 6px 0 0;
    padding: 0 20px;

    background-color: #F6E9D8;
}