Blorf
Blorf

Reputation: 546

Keep last two elements wrapping together

I have a dynamically generated UL/LI list with a variable number of elements in it, displayed horizontally. I want to set up my CSS so that if wrapping is needed, the last two elements in the list always wrap together.

Markup:

<ul>
<li>A</li>
<li>B</li>
...
</ul>

Output

Displays in one line when there's enough space: 
A B C D E F G

Breaks like this first when shorter:
A B C D E
F G

This is fine, too:
A B C D
E F G

NEVER THIS:
A B C D E F
G

The space the list uses is responsive and the elements are dynamic, so nothing fixed-width will help. I don't have control of the markup because it comes from a CMS. My list items are currently floated, but changing to flex or inline-block is fine.

Is this possible in pure CSS?

Upvotes: 3

Views: 1207

Answers (2)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

This is possible in CSS.

  1. Set the ul's min-width equal to the space needed for the last two elements.
  2. Set the margin-right of the next-to-last li equal to the width of the last li.
  3. Set the margin-left of the last li equal to the negative of its width.

Example Fiddle

CSS:

ul {
  min-width: 4em;
}

li {
  float: left;
  width: 2em;
}

li:nth-last-of-type(2) {
  margin-right: 2em;
}

li:nth-last-of-type(1) {
  margin-left: -2em;
}

Upvotes: 5

lopezi
lopezi

Reputation: 547

Use flex-wrap property, it will adjust spacing automatically.

ul{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

Upvotes: 0

Related Questions