Reputation: 546
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
Reputation: 35670
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.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
Reputation: 547
Use flex-wrap property, it will adjust spacing automatically.
ul{
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
Upvotes: 0