I have some elements inside a DIV
which get reordered depending on the size of the screen. I want to style each of these elements differently depending on their flex-box order. Because the media queries are inside a framework, I'd rather not write my own media queries to do this, because I don't want to have to remember to change my media queries if the framework changes the break points for their media queries. I tried using the +
sibling selector, but apparently this only applies to the order of elements in the original markup, not the flex box rendering order. Is there any way to style an element based on the order in which it appears in the rendered DOM?
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.
Use of the order property has exactly the same implications for accessibility as changing the direction with flex-direction . Using order changes the order in which items are painted, and the order in which they appear visually.
Justify Content Flex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.
Use justify-content utilities on flexbox containers to change the alignment of flex items on the main axis (the x-axis to start, y-axis if flex-direction: column ). Choose from start (browser default), end , center , between , or around . Responsive variations also exist for justify-content .
As mention in the comments, you wont be able to use nth-child, as the styles will apply to the order of the actual DOM, not the rendered DOM.
You will have to add extra classes to the markup in order to do this. So rather than re-order using nth-child, re-order using the extra classes.
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.flexGrid {
display: flex;
flex-wrap: wrap;
width: 100%;
}
.flexGrid__item {
border: 1px solid pink;
width: 50%;
height: 100px;
}
.flexGrid__item--alpha {
background: pink;
order: 1;
}
.flexGrid__item--bravo {
order: 2;
}
.flexGrid__item--charlie {
order: 3;
}
.flexGrid__item--delta {
order: 4;
}
@media screen and (min-width: 500px) {
.flexGrid__item {
width: 25%;
}
.flexGrid__item--alpha {
order: 5;
}
}
<div class="flexGrid">
<div class="flexGrid__item flexGrid__item--alpha"></div>
<div class="flexGrid__item flexGrid__item--bravo"></div>
<div class="flexGrid__item flexGrid__item--charlie"></div>
<div class="flexGrid__item flexGrid__item--delta"></div>
</div>
More detail in this fiddle: https://jsfiddle.net/pua5u8a4/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With