Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep last two elements wrapping together

Tags:

css

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?

like image 632
Blorf Avatar asked May 10 '26 12:05

Blorf


1 Answers

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;
}
like image 65
Rick Hitchcock Avatar answered May 12 '26 00:05

Rick Hitchcock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!