SQRCAT
SQRCAT

Reputation: 5840

How to target the last element before break occurs in a flexbox design?

Imagine this layout:

[BOX]  [BOX]  [BOX]
[       BOX       ]

Which is a flexbox design, and – if the screen shrinks – will look like this:

[  BOX  ] [  BOX  ]
[       BOX       ]
[       BOX       ]

And would become a set of 4 rows if the screen is too narrow to display even two boxes next to one another.

So far so good.

I am looking for a way to target the last element in the upper row, no matter how the flexbox has currently adjusted to its environment.

Naturally i thought of CSS pseudo-classes, but i was unable to find anything other than the typical ones, such as :last-child and :last-of-type or :nth-child, which would not help in this situation.

QUESTION

Is there a way to do this purely in CSS? If yes, how?

Upvotes: 8

Views: 2847

Answers (3)

pandey909
pandey909

Reputation: 1189

you can use nth-of-type() pseudo-selector, combining with media-queries. Check out: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type

Upvotes: 0

FelipeAls
FelipeAls

Reputation: 22161

You can't detect and target a flex item but you can add a :pseudo to the flex container and position it at upper right.
Which will probably not help: what do you want to do with that end of upper row?

Other ways of doing things there:

  • flex-direction: row-reverse will display flex items from right to left. You now have to target the first item. It'll mess the tab order of links and form fields for people using a keyboard which causes accessibility problems. But tabbing blocks from right to left may be acceptable if there aren't forms and/or dozens of links.
  • flex-wrap: wrap-reverse will wrap from bottom to top. Upper right is now your last flex item but the first row is at the bottom with 2-4 items and the top one will probably have only one item. Probably not the layout you expect. Also it'll mess the tab order of links and form fields for people using a keyboard which causes huge accessibility problems in this case (focus will jump 2 screens below and will go back before a new 2 screens-high jump… Ouch).
  • Grid layout and auto-fill/auto-fit and constraints on widths could allow you to guess which grid item is last in the first row, but you lose flex: grow shrink basis% provided by Flexbox.

Upvotes: 1

Michael Benjamin
Michael Benjamin

Reputation: 371183

You could conceivably use a media query to target the second item after the subsequent items have wrapped. Barring that option, it's not possible with CSS.

Wrapping is not a behavior that is tracked by CSS. For example, a container has no idea when its children wrap. Therefore, there is no way to target items with CSS based on wrapping scenarios (except with media queries, as mentioned above).

More details here: Make container shrink-to-fit child elements as they wrap

Upvotes: 5

Related Questions