Search code examples
csslistmenuwidthautosize

CSS - Have each item in a horizontal list have an equal share of the available padding


Consider a simple CSS layout, where containing wrapper div defines a fixed width of 900 or so pixels, everything inside it therefore expands to 100% width.

In here, I have a navigation div, containing 1 UL and 6 list items, left-floated so they appear in a line horizontally.

Each list item should growing variably to fit its text contents exactly, but the spacing between each item should be shared so that the whole menu fits into the 100% space, such as:

------------------------------------------------------
-N-        -N-          -N-               -N-      -N-
- -        - -          - -               - -      - -
- -ITEM1111- -ITEM222222- -ITEM33333333333- -ITEM44- -   
- -        - -          - -               - -      - -
------------------------------------------------------
<-------------------- 100% -------------------------->   

I hope that is illustrative! 'N' is constant but grows to fit the 100% width accordingly (i.e. for accessibility - someone increases the font size).

Happy to take alternative suggestions although I'm aiming for no javascript or images, just css purity.


Solution

  • Here is my simple solution for this based on CSS3 Flexible Box Layout:

    Styles

    ul {
        padding: 0;
        width: 100%;
    }
    
    ul li {
        list-style: none;
        text-align: center;
        border: 1px solid Gray;
    }
    
    .flexmenu {
        display: -webkit-box;
        display: -moz-box;
        display: box;
    }
    
    .flexmenu li {
        -webkit-box-flex: 1;
        -moz-box-flex: 1;
        box-flex: 1;
    
        -webkit-flex-basis: auto;
        -moz-flex-basis: auto;
        flex-basis: auto;
    }
    

    HTML

    <div style="width:900px">
        <ul class="flexmenu">
            <li>short</li>
            <li>looooooooooooooooooooooooooooooong</li>
            <li>short</li>
            <li>short</li>
        </ul>
    </div>
    

    Result

    enter image description here