How can I get a
    to be evenly spaced across th

2019-04-29 00:31发布

问题:

I have a List that I'm using as a list of tabs:

<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>

where the CSS is defined as follows:

#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;
}

This list only takes up about 90% of the width available to it on the page, where everything else in the page takes up 100% of the width because they're laid out in divs. The space avaiable to them is defined in an element supplied by the client at

 width: 62.1em

Basically what I need is to get the tabs to be distributed evenly so they fill the entire width available to them, with the text/link aligned in the middle of each tab? Is there a way for me to do this?

回答1:

But of course. I've put together a demo here. The CSS is as follows with explanation as comments:

#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;
}