Friday 29 January 2021

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

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

.a-fc {
  background-color: purple;
  width: 300px;
  /*height: 100px;*/
}

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

.b-fc > * {
  flex-grow: 1;
  flex-basis: 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>

FC = flex-container. FI = flex-item.

I am able to place .b-fc onto a new row when the space left for it to exist on the original row goes below 70px.

My task: I want b-fc's FIs to stack vertically when no new row is created/they don't wrap. I want b-fc's FIs to align horizontally when b-fc wraps.


Current solution

In the code-snippet above, I've tried to achieve my task by writing one set of properties that work for both scenarios by setting a `flex-basis` on `.b-fc`'s FIs. If the space left for `.b-fc`'s FIs is less than this flex-basis (100px), the FIs will stack vertically. The weakness: i) if `.b-fc`'s `width`'s larger than 300px, its FIs align horizontally ii) When `.b-fc` wraps, its FIs wrap when `.bf-c` is less than 300px.

Therefore, I'm figuring it'd be more powerful to be able to apply CSS when .b-fc wraps. Is this possible?

*Idea 1: CSS variables & JS*

Perhaps using CSS variables/SASS I could continually assess whether FC - .a-fc <= than 70px. If true, apply stylings to .b-fc.

Idea 2: media-queries

Another option is to test when row2 is made, use media queries to capture this and apply CSS to .b-fc with media queries.


P.S. Similar question has been asked here before in 2015. Maybe new techniques have transpired since.



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

No comments:

Post a Comment