Order flex item at last position always

Viewed 1573

I have a flex container like below :

<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    .
    .
    .
    <div class="child">n</div>
</div>

the child number varies everytime. I need second child to always be at last in mobile device.

I am aware order: -1 can be used to place it at first place everytime. But I'm interested in knowing if there's anything I can do to order it at last position everytime.

1 Answers

Normally the elements are laid out in the order of their appearance in the markup. However you can specify an implicit ordering using the order property in css. This will place elements according to their order. If two elements have the same value for this order property, they will stay be layed out following the original markup. In a way you can see it as form of grouping: first the ones with order 0, then with order 1, .... (setting a negative value for order would of course place them before the 0 group; that is how the -1 trick to place the element first works)

You can use this solve your problem by simply setting the order of the second child to 1, all other elements will have the default value of 0 so be placed before.

.child:nth-child(2) {
  order: 1;
}
Related