DEV Community

loading...

Randomising Flex Order of Items

Gavin Sykes
Emerging web dev, football fan and devoted husband and father, also enjoys cooking.
Updated on ・2 min read

This all stems from a random conversation this week, where a colleague was fiddling with the layout of our new website. She essentially wanted a row of vendor logos to display, but in the era of responsive web design, not cram 8 of them onto a mobile screen, and not use 3 of them to fill up a laptop, so our initial idea was to simply use media queries to hide/show certain ones.

Not bad, but not brilliant, it just seems a bit static and there's too much chopping and changing, we could do with it being a bit more fluid. That's when she came up with these 2 brilliant lines of code that got rid of the need for any media queries at all!:

.logos-container {
  /* other styles such as display: flex; and flex-flow: row wrap; */
  height: same-as-logos-height; /* They're all png files set to the same height */
  overflow: hidden;
}
Enter fullscreen mode Exit fullscreen mode

So that's the cramming issue sorted, and all these logos can now be displayed on a large screen, with only 2 or 3 of them on a mobile. But now there's another problem:

A mobile user will only ever see the first 2 or 3 logos that are in the markup, and may never see the rest of the vendors we work with!

Kate: "It would be good to be able to randomise these."

Me: "Well there's flex-order that can change the order of how things appear no matter where they are in the markup, so I reckon that would be the answer. Randomising though? I'm not sure CSS can do that."

Enter JavaScript.

Me: "I promise you, there is a way to do this and I will find that way."

Me a few days later: "Here it is!":

This was also my first step into using either a CSS or HTML preprocessor. I'd always viewed these tools in the past with a "well, what's the point?" attitude, but have started slowly warming to them. Certainly, HAML's ability to do for loops and create a lot of divs without having to change x lines of code to tweak them all slightly I found very helpful. Plus, change one number and you get more or fewer items, no mass deletion and no copying and pasting multiple times! SCSS is also another string to the bow, and I believe its ability to manage large-scale projects may well come in useful in the future.

Discussion (0)