Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS flex-wrap: Put gap between items unless wrapped?

Tags:

html

css

flexbox

I come often across with this scenario, where i have i.e. 2 flex-children, with property flex-direction row. so they are first shown side by side with a gap between them (margin-right).

And by resize, as soon as there is not enough space left for both, flex-wrap moves the second child under the first one, so i don't need the margin-right from 1. item anymore.

Can i dynamically set the margins depends on the "wrap" status?

Fiddle: https://jsfiddle.net/ejmhxztd/

Fiddle Note: You should resize the window (reduce width) and see the wrapped case. If you continue reducing the width, you will see that the text of the first child will also split into 2 lines, since the margin-right is there and takes space.

.parent {
  display:flex;
  flex-direction:row;
  flex-wrap:wrap
}

.child1 {
  margin-right:300px
}
<div class="parent">
   <span class="child1">Child1 Text</span>
   <span class="child2">Child2 Text</span>
</div>
like image 922
akcasoy Avatar asked Aug 27 '26 18:08

akcasoy


1 Answers

I know this is an old issue, but you can use "column-gap" and "row-gap" to define gaps only in some direction.

For example:

.class{
  display: flex;
  align-items: center;
  column-gap: 10px;
  flex-wrap: wrap-reverse;
  flex-direction: row;
}

In this case, the gap will only affect in columns.

like image 137
Cafn Avatar answered Aug 30 '26 07:08

Cafn