سؤال

I'm looking for a way to make a horizontal menu in which the menu items are justified across the width, have padding, and overflow to a new line when the number of menu items exceed the container space.
HTML:

<div id='upper-menu-wrapper'>
<div id='upper-menu'>
    <ul>
        <li>About</li>
        <li>Parenting</li>
        <li>Receipes</li>
        <li>Devotional</li>
        <li>DIY Projects</li>
        <li>Home-making</li>
        <li>Pregnancy</li>
        <li>Frugal Living</li>
    </ul>
 </div>
</div>

CSS:

#upper-menu-wrapper {
    width: 100%;
}
#upper-menu {
    width: 1200px;
    margin: 0 auto;
    overflow: auto;
}
#upper-menu > ul {
    list-style-type: none;
    text-align: justify;
    width: 100%;
}
#upper-menu > ul > li {
    display: inline-block;
    padding: 1em;
    text-align: center;
}
هل كانت مفيدة؟

المحلول

Getting the elements to justify with wrapping to next line is tricky. Using display:table and table-cell can justify elements like tables but only in one row. Because your requirement is to also keep elements justified while wrapping within a fixed width container, the table-cell won't work.

There is a hack based on :after pseudo-element which can make this possible with wrapping across rows.

Demo: http://jsfiddle.net/abhitalks/MXZ6w/3/

Apply a fixed width to the wrapping div, text-align:justify on the ul and display:inline-block on li are required.

#upper-menu-wrapper {
    width: 500px; /* fixed width on wrapping container */
}
#upper-menu { } /* this div is not really needed */

#upper-menu > ul {
    list-style-type: none; /* getting rid of bullets */
    margin: 0px; padding: 0px; /* getting rid of default indents */
    text-align: justify; /* important to justify contents */
}
#upper-menu > ul > li {
    display: inline-block; /* required. float won't work. */
    text-align: left; /* to properly align list items */
    white-space: no-wrap; /* to prevent wrapping of list items if required */
}

#upper-menu > ul:after { 
    /* this is the hack without which the list items won't get justified */
    content:''; display: inline-block; width: 100%; height: 0; 
}

Note 1: The display: inline-block is required, however it generates html white-spaces. In order to get rid of those white-spaces, html comments can be used in the markup of list items.

Note 2: The :after pseudo element in the hack is what seems to do the trick. However, that will create an unintended space below the ul. This space seems to be there because the elements are flushed across. If not justified, then this space does not appear.

IMPORTANT: Credit: @SamGoody from his answer here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top