sdimitrijevikj
sdimitrijevikj

Reputation: 1460

CSS3 columns not spreading appropriately

The problem occurs when I try to use a list with 3 columns and it contains 4 items.

jsFiddle example here.

The following is the code used:

ul {
    -webkit-column-count: 3;
    -moz-column-count: 3;
    column-count: 3;
    list-style: none;
}

And the HTML:

<ul>
<li> item1 </li>
<li> item2 </li>
<li> item3 </li>
<li> item4 </li>
</ul>

The expected result is:

item1 | item3 | item4
item2

But the result looks like this:

item1 | item3
item2 | item4

It would be nice if I could get some insight as to why that is and if there is a way to fix this issue. Also I am fully aware that I can fix this with a simple float approach but I am interested in a solution that would involve the CSS3 columns approach.

Edit: Regarding the duplicate votes i should add that when the list has more or less than 4 items it works fine. It is only when i have 3 columns and 4 items that i encounter this silly issue.

Upvotes: 0

Views: 178

Answers (2)

FelipeAls
FelipeAls

Reputation: 22181

A solution is to add to the 4th and last item a pseudo with some height: the pseudo will stay in the 2nd column and the 4th and last item is finally displayed in the 3rd column.

Codepen with some other cases which shouldn't be modified

Relevant CSS:

li:nth-child(4):last-child:before {
  content: '';
  display: block;
  width: 100%;
  height: 1px;
  background-color: red;
}

Edit: it won't play nice with overflow: hidden and maybe other properties giving Block Formatting Context to items (or maybe it's just overflow: hidden)

Why > Joseph Young already answered that part imho. Codepen with 4 columns and 4 to 7 items also shows that with 5 or 6 items, there are only 3 columns filled

Upvotes: 0

Joseph Young
Joseph Young

Reputation: 2785

I haven't read any specs, but I think the way it works it out is by getting the number of items(= 4) and dividing it by the number of cols(=3) to get the max number of rows(ceil(4/3)=2).

It then starts filling up the columns and once they hit this row limit, they move onto the next column. Obviously, 4 items can only fill 2 columns each 2 rows high. If you add another item, it will flow into the third column.

If you imagine it as trying to greedily fill columns rather than rows, it makes sense as to why it does it. I suppose it just wasn't meant to be used the way you want to use it

Upvotes: 2

Related Questions