How to Detect CSS Flex Wrap Event

How to tell if flex-item is being wrapped

The solution that seems best to me, is to add an attributed "wrapped" to each flex child once they are wrapped, and remove it when they are not wrapped. This can be done by comparing the width of the flex-container to the sum of the widths of the flex-children. I'll post a code snippet once I finish writing it.

There ought to be an attribute added to wrapped flex items by the browser.

Can I apply CSS to a flex-item when it wraps onto a new row?

For this particular case you can consider the use of max() combined with flex-basis. The trick is to either have 0px (horizontal item) or a very big value (vertical items).

You will note that this is not a generic solution and the value is based on your html structure:

395px = 300px (width of a-fx) + 70px (flex-basis of b-fc) + 10px (border of wrapper) + 16px (default body margin) - 1px

.wrapper {
border: 5px solid pink;
display: flex;
flex-wrap: wrap;
justify-content: center;
}

.a-fc {
background-color: purple;
width: 300px;
}

.b-fc {
background-color: orange;
display: flex;
flex-wrap: wrap;
flex-basis: 70px;
flex-grow: 1;
}

.b-fc>* {
flex-grow: 1;
flex-basis: max(0px, (100vw - 395px)*100);
height: 100px;
}

.b-fc>*:nth-child(1) {
background-color: red;
}

.b-fc>*:nth-child(2) {
background-color: blue;
}

.b-fc>*:nth-child(3) {
background-color: green;
}
<div class="wrapper">
<div class="a-fc">
<div>a1</div>
</div>
<div class="b-fc">
<div>b1</div>
<div>b2</div>
<div>b3</div>
</div>
</div>

Use flex wrap with stretch elements as rows

To correct your code (The second method will be more responsive on small screen):

  • Either just add width: 50%; to .item, as in first demo below.
  • Either just modify min-width: 100px to min-width: 50%;

But I would recommand you to use display:grid; as in second Demo (code is much more simple.

DEMO based on your code:

.container {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
align-items: stretch;
align-content: stretch;
justify-content: center;
position: fixed;
}

.item {
min-width: 100px;
min-height: 100px;
display: flex;
flex-direction: column;
justify-content: center;
position: relative;
flex-grow: 1;
width: 50%;
}
.item:nth-child(1){
background: red;
}
.item:nth-child(2){
background: green;
}
.item:nth-child(3){
background: blue;
}
.item:nth-child(4){
background: yellow;
}
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>


Related Topics



Leave a reply



Submit