When working with the current markup and utilizing the nowrap
property, the only way to exclude the last item at a specific width is by applying position: absolute
.
However, this approach would require a script to adjust the height of the container
to avoid other elements from being positioned below it.
.flex-parent {
position: relative;
display: flex;
justify-content: space-between;
}
@media (max-width: 700px) {
.flex-item:last-child {
position: absolute;
left: 0;
top: 100%;
}
}
/* just for this demo, to create space between "container"'s */
.container + .container {
margin-top: 30px;
}
<div class="container flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
<div class="flex-item">
ITEM 3
</div>
<div class="flex-item">
ITEM Last
</div>
</div>
<div class="container flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
<div class="flex-item">
ITEM 3
</div>
<div class="flex-item">
ITEM 4
</div>
<div class="flex-item">
ITEM 5
</div>
<div class="flex-item">
ITEM Last
</div>
</div>
<div class="container flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
<div class="flex-item">
ITEM Last
</div>
</div>
If a modification to the markup is allowed, one alternative solution is to wrap all items except the last one in a parent container and then toggle the flex-direction
property with a media query.
To ensure that space-between layout works in both wrapped and unwrapped scenarios, a pseudo
element is used in conjunction with setting the inner flex-parent
to fill the remaining space using flex: 1
.
Stack snippet
.flex-parent {
display: flex;
justify-content: space-between;
}
.container .flex-parent {
flex: 1;
}
.container .flex-parent::after {
content: '';
}
@media (max-width: 700px) {
.container.flex-parent {
flex-direction: column;
}
.container .flex-parent::after {
display: none;
}
}
/* just for this demo, to create space between "container"'s */
.container + .container {
margin-top: 30px;
}
<div class="container flex-parent">
<div class="flex-item flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
<div class="flex-item">
ITEM 3
</div>
</div>
<div class="flex-item">
ITEM Last
</div>
</div>
<div class="container flex-parent">
<div class="flex-item flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
<div class="flex-item">
ITEM 3
</div>
<div class="flex-item">
ITEM 4
</div>
<div class="flex-item">
ITEM 5
</div>
</div>
<div class="flex-item">
ITEM Last
</div>
</div>
<div class="container flex-parent">
<div class="flex-item flex-parent">
<div class="flex-item">
ITEM 1
</div>
<div class="flex-item">
ITEM 2
</div>
</div>
<div class="flex-item">
ITEM Last
</div>
</div>