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?
This is possible in CSS.
ul's min-width equal to the space needed for the last two elements.li equal to the width of the last li.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With