Space-between and flex-end together
When using justify-content: space-between in a flex box component, you end up with something like the image below. Essentially, it allows the elements to be spread out inside their container… adding space between each element.

The problem, I’ve sometimes butted up against, is when I want that behaviour on a list of elements that could vary their number all the way down to 1.
When that container only contains one element, that element aligns to the left, just like if I’d set justify-content: flex-start.

But I sometimes want it to align to the right. If I assign justify-content: flex-end I can get that behaviour when I have one item, but it will no longer give me space-between when there is more than one element.


The problem is, both values are applied to justify-content. So how do we apply space-between and flex-end at the same time?
An attempted solution
One approach might be to give the elements a left margin of auto. This works similar to the space between, and means that when there is only one item, the space increases to push to the far right.
.container {
display: flex;
justify-content: space-between;
}
.container div {
margin-left: auto;
}

But, as you can see below, it also causes the space-between gap to be applied to the left of the element even when there is more than one. Which is not what we want.

A weird solution
One solution I’ve used before is rather counter-intuitive. We can change the flex-direction to row-reverse.
.container {
display: flex;
justify-content: space-between;
flex-direction: row-reverse;
}
.container div {}

This literally tells all elements in the flex container to flow in the other direction. It’s similar to changing the read direction from left-to-right, to right-to-left.
It works perfectly spacing-wise, and will look visually correct, but be aware that it will also change the visual order of the elements. So you’ll need to correct that by changing the order of the data passed in.

That’s it!
Thanks…
I also dissect and speculate on design and development.
Digging into subtle details and implications, and exploring broad perspectives and potential paradigm shifts.
Check out my conceptual articles on Substack or find my latest below.
You can also find me on Threads, Bluesky, Mastodon, or xTwitter for more diverse posts about ongoing projects.

Leave a Reply