CSS spread <li> horizontally across <ul>
Asked Answered
C

5

5

I'm trying to spread a list of <li>'s aligned horizontally using float:left across my <ul>.

Does anyone have any idea how this is done?

Chuchuah answered 20/8, 2011 at 10:56 Comment(3)
float: left; sounds good. What HTML/CSS do you have so far?Brigandage
@Brigandage I was actually trying to divide them evenly, e.g. they will all have the same width regardless of their content, together adding up to the <ul>'s width.Chuchuah
best answer: https://mcmap.net/q/1921300/-spread-dynamic-menu-on-full-page-widthTypewrite
S
8

Is there some reason why you can't just set them to display: inline; (or inline-block)? For example:

http://jsfiddle.net/TKmR5/

Sherrill answered 20/8, 2011 at 11:2 Comment(3)
Display inline creates an awkward space between items, it also disallows to set width or height.Chet
Then use inline-block instead! "awkward space between items" is caused by not re-setting margins and paddings…Tess
I was able to figure out something similar myself, but this is not what I were looking after. I want differently sized items, but spread over a set width.Chuchuah
C
7

The answer is to use display: table; on the <ul> element and display: table-cell; on the <li> elements.

Chuchuah answered 24/12, 2013 at 10:34 Comment(2)
Wow didn't even know this after all this time. Thank you!Halutz
This doesn't work, would be interested in seeing a codepen or fiddle to see what else was added to styling in order to get it to work this way.Opt
O
2

You can use display: inline-block; it works in modern browsers.

Example: http://jsfiddle.net/joar/ELpDD/

As feela said in the comments to #7131346,

[…] "awkward space between items" is caused by not re-setting margins and paddings…

Overlying answered 20/8, 2011 at 11:21 Comment(0)
I
1

Float left and divide the width of the ul over de number of lis I think is what you are after. Have a look here: http://jsfiddle.net/b2nsW/

HTML:

<ul>
    <li>item</li>
     <li>item</li> 
     <li>item</li> 
     <li>item</li> 
</ul>

CSS:

ul {
    width: 250px;
    background: red;
    padding: 0;
    margin: 0;
    overflow: auto;
}

li {
    width: 20%;
    float: left;
    background: green;
    margin: 2.5%;
}
Idioblast answered 20/8, 2011 at 11:12 Comment(1)
Working, but only useful, if you have a fixed number of menu-items. But a customer may add more menu-items via a CMS.Tess
S
1
li {
    display: inline-block;
}

ul{
    text-align: center;
}

Then adjust the padding or margins of the li elements to spread them across less or more across the ul.

Selfpossessed answered 6/2, 2016 at 3:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.