Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

flexbox

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?

like image 982
SquareCat Avatar asked Jun 20 '18 23:06

SquareCat


People also ask

Can we change the order of Flex items?

Flex items are displayed in the same order as they appear in the source document by default. The order property can be used to change this ordering.

What element do you target flexbox to?

Flexbox is different from many other CSS properties: instead of targeting an element and acting directly upon it, we target the parent element and that controls the layout of its children. We're making a flex container and all the children of that container become flex items.

How do you make a flex item break to the next line?

The solution is to force them by adding a collapsed row (height 0) which takes up the entire width of the container, making it occupy an entire row, thus pushing the 3rd item on the next row. Think of it like a <br> tag.


1 Answers

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

like image 169
Michael Benjamin Avatar answered Oct 07 '22 01:10

Michael Benjamin