0

I have a flexbox with wrap enabled, and various flex basis and flex grow constaints.

By default, it looks like this:

[ A, B ]

but under a certain screen size, it wraps to this:

[ A,
  B ]

Which is exactly what I want.

My question is: is it possible to set a background color on B only in the first instance, when it doesn't wrap? Basically, if it's part of a single row, I want it to have a background color with a tone complementing A, but if it wraps I want the background to be white.

Is this possible? Or do I need to resort to media queries?

Nathan
  • 73,987
  • 14
  • 40
  • 69
  • 2
    Does this answer your question? [Can flexbox detect when a flex item wraps?](https://stackoverflow.com/questions/43420603/can-flexbox-detect-when-a-flex-item-wraps) – IT goldman Oct 12 '22 at 22:32
  • @ITgoldman potentially? I don't know if the answer to that question means that my question is definitely impossible, though it suggests it. – Nathan Oct 12 '22 at 23:32
  • 1
    There's nothing in CSS to target B when it wraps. You'll need media queries or JS. The suggested link above is right. This question is a duplicate of that post. – Michael Benjamin Oct 13 '22 at 03:14
  • 1
    Nice try Nathan but without javascript it's not possible. *With* javascript you can detect height of element on resize event or something like that. – IT goldman Oct 13 '22 at 05:59
  • Fair enough. I ended up just biting the bullet and using a media query, but it's definitely a shame flex wrap can't be detected/responded to in CSS. If you want to close this question, that's fair, but I'll leave it up for now. I tend to favor leaving multiple paths to a solution, I'll answer this one myself. – Nathan Oct 13 '22 at 06:04

1 Answers1

0

No, it is not possible just with CSS, unfortunately. See the question Can flexbox detect when a flex item wraps?

If you want to do this, you'll need to set style using a media query (that styles the background based on the size breakpoint that will result in wrapping). Alternatively, you can hook into the dimensions of the element with javascript, and add/remove classes programmatically based off of that-- though that would potentially cause a delay during loading or reflow.

Nathan
  • 73,987
  • 14
  • 40
  • 69