A couple of pseudo-elements will accomplish that:
flex-container {
display: flex;
justify-content: space-between;
background-color: orangered;
}
flex-item {
flex: 0 0 20%;
height: 100px;
margin: 5px 0;
background-color: lightyellow;
}
flex-container::after {
content: '';
}
flex-container::before {
content: '';
}
<flex-container>
<flex-item></flex-item>
<flex-item></flex-item>
<flex-item></flex-item>
</flex-container>
Most, if not all, browsers interpret pseudo-elements on a flex container to be flex items. The ::before
pseudo is the first item, and the ::after
is the last.
Here's a reference from Firefox documentation:
In-flow ::after and ::before pseudo-elements are now flex
items
(bug 867454).
The code above works because justify-content: space-between
now factors in five flex items, but the first and last have 0 width.
I'm not sure this can be made to work in a multi-line container (flex-wrap: wrap
) with pure CSS. You can try using auto
margins on flex items instead of justify-content
on the container. Otherwise, JavaScript.