CSS align items to the end with wrapping

Viewed 77

I have a fixed-width container and I want to display a dynamic amount of same-sized items that should be aligned to the right side of the container.

enter image description here

When there are too many items, they should wrap into multiple lines. However, I want the bottom lines to fill completely and the top-most line with the remaining space.

enter image description here

I thought I could achieve this with flex layout (like justify-content: flex-end;), but I didn't succeed.

How (if possible) could I produce the desired placement with CSS rules?

HTML can be assumed to be very basic:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <!-- ... -->
  <div class="item">N</div>
</div>

Note: all items have the same dimensions, I just didn't draw them accurately in the images.

2 Answers

You can use SASS to generate the code that will switch the order of all the elements:

$n:100;
@for $i from 1 through $n {
 .container > div:nth-last-child(#{$i}) {order:#{$i}}
}

Example:

.container {
  display:flex;
  flex-wrap:wrap-reverse;
  flex-direction: row-reverse;
}

/* generated with sass*/
.container > div:nth-last-child(1) {
  order: 1;
}

.container > div:nth-last-child(2) {
  order: 2;
}

.container > div:nth-last-child(3) {
  order: 3;
}

.container > div:nth-last-child(4) {
  order: 4;
}

.container > div:nth-last-child(5) {
  order: 5;
}

.container > div:nth-last-child(6) {
  order: 6;
}

.container > div:nth-last-child(7) {
  order: 7;
}

.container > div:nth-last-child(8) {
  order: 8;
}

.container > div:nth-last-child(9) {
  order: 9;
}

.container > div:nth-last-child(10) {
  order: 10;
}

.container > div:nth-last-child(11) {
  order: 11;
}

.container > div:nth-last-child(12) {
  order: 12;
}

.container > div:nth-last-child(13) {
  order: 13;
}

.container > div:nth-last-child(14) {
  order: 14;
}

.container > div:nth-last-child(15) {
  order: 15;
}

.container > div:nth-last-child(16) {
  order: 16;
}

.container > div:nth-last-child(17) {
  order: 17;
}
/**/

/* irrelevant styles */
.container > div {
  width:80px;
  height:60px;
  margin:5px;
  color:#fff;
  background:red;
}
.container {
  counter-reset:num;
}
.container > div::before {
  content:counter(num);
  counter-increment:num;
}
<div class="container">
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
</div>

Related