Quantity Ordering With CSS

Here is your mission, should you choose to accept it: create a table of items. Each item should span a third of the content area, with the fourth item starting on a new row, much like floats. However, a particular item must always display the price at the end of the first row.

Visually, we want to achieve this:

css-quantity-ordering

Note the blueish item with the green outline at the end of the first row. Even though it’s declared last in in the HTML, it’s positioned at the end of the first row, no matter how many other elements the list holds. Using quantity selectors and Flexbox’ order property, the CSS needed to achieve this is:

// Note: outline added for visual reference

// All items: Set the order to 1.
// Note: Items that have the same CSS `order` value will appear in the order as they are declared in the HTML.
.container .item {
  order: 1; /* This is the default, no need to explicitly declare it */
  outline: 1px solid blue;
}

// If there are more than 3 items, set the CSS order of that third item and its successive items to 3. That way a tiny gap in the CSS order sequence is created.
.container .item:nth-child(n+3) {
  order: 3;
  outline: 1px solid red;
}

// If there are more than 3 items, move .time in between the first two and all other items by setting the CSS order to 2. That way it'll squeeze in between the items with CSS order 1 and CSS order 3, giving us the wanted result
.container .item:nth-last-child(n+3) ~ .time {
  order: 2;
  outline: 1px solid lime;
}

Here’s the resulting pen:

Check out this Pen!

Quantity Ordering With CSS →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.