Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snake-like alignment in css

Tags:

css

I have been struggling with the following problem in CSS. I have an arbitrary number of items (spans or divs) that I want to wrap inside a container in a snake-like pattern.

What I mean by this is that if I have 10 items, which are each 20px wide, I would like them to display as follow in a 60px wide container:

0 1 2
5 4 3
6 7 8
    9

I have tried using flexbox in CSS, but I can only get the items to display like this:

0 1 2
3 4 5
6 7 8
9

If that can help, I know the exact width of the individual items, but I do not know the width of the container.

Any help would be much appreciated.

Thank you in advance!

like image 242
Andreq Avatar asked Dec 09 '16 16:12

Andreq


2 Answers

If you create your HTML structure with parent - rows - items you can use flex-direction: row-reverse on .row:nth-child(2n) elements and that will create desired result.

.content {
  display: flex;
  flex-direction: column;
}
.row {
  display: flex;
  justify-content: space-between;
}
.row:nth-child(2n) {
  flex-direction: row-reverse;
}
.row:nth-child(2n):last-child .item {
  margin-right: auto;
}
<div class="content">
  <div class="row">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
  </div>
  <div class="row">
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
  </div>
  <div class="row">
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
  </div>
  <div class="row">
    <div class="item">10</div>
  </div>
</div>
like image 54
Nenad Vracar Avatar answered Oct 16 '22 02:10

Nenad Vracar


Without knowing your markup limitations, you could use the following structure and float values to make it work.

.ltr, .rtl {
  width: 60px;
}
.ltr div, .rtl div {
  width: 20px;
  height: 20px;
  display: inline-block;
}
.rtl div {
  float: right;
}
.ltr div {
  float: left;
}
<div class="ltr">
  <div>0</div><div>1</div><div>2</div>
</div>
<div class="rtl">
  <div>3</div><div>4</div><div>5</div>
</div>
<div class="ltr">
  <div>6</div><div>7</div><div>8</div>
</div>
like image 28
Dryden Long Avatar answered Oct 16 '22 01:10

Dryden Long