Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evenly space elements within a variable-width parent (over multiple lines)?

Tags:

html

css

list

So I have an UL in my website with around 30 list items, each list item contains an icon which is around 130px in width so the list extends into multiple rows.

The issue I am having is hard to explain so ill try using this jsfiddle.

    ul { 
       display: table; margin: 10px auto; 
    }

    li { 
       float: left; list-style: none; margin-left: 5px; padding: 5px 0; 
    }
    li a { 
       background: #82B5DA; 
       border: 1px solid #599CCE; 
       border-radius: 3px; 
       padding: 5px; color: #333; 
       text-decoration: none; 
}

So what I want is for the space between each of those list items to be dynamic and make it so the list item that is far RIGHT touches the edge of the screen instead of a gap appearing until there is enough space for a new list item. Once there is enough room for another list item to go on that row, the width between the items is reset.

Resuming, turn this:

|[aaaaaaaaa][bbbbbbbbbb][cc]       |
|[dddddddddddddddddddbb][eeeee]    |

In this:

| [aaaaaaaaa]  [bbbbbbbbbb]  [cc] |
| [dddddddddddddddddddbb]  [eeeee]|

Hopefully that makes sense, new to posting here so apologies if this isn't correct in some way.

like image 969
Dean Johnstone Avatar asked Mar 15 '14 01:03

Dean Johnstone


2 Answers

If I understand what you're after, then you can use a flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

like so:

ul {
    display: flex;
    margin: 10px auto;
    padding: 0 10px;
    flex-wrap: wrap;
    justify-content: space-between;
}

demo: http://jsfiddle.net/5grwG/19/

HOWEVER, support is currently fairly limited (http://caniuse.com/flexbox) so this only really works if you can find a decent polyfill, or are just looking to support the latest browsers.

like image 97
Ben Jackson Avatar answered Sep 22 '22 03:09

Ben Jackson


As far as I know, it can be achieved only using javascript.

Try Isotope plugin. Minimized version is around 15kb.

https://github.com/desandro/isotope/blob/master/jquery.isotope.min.js

like image 29
PrivateUser Avatar answered Sep 23 '22 03:09

PrivateUser