Dicky Bullin
Dicky Bullin

Reputation: 257

CSS table layout with n rows and expanding as columns

I have been struggling with this CSS layout. I have n items that its amount might increase dynamically. And I want to only just have n rows and many or unlimited columns layout.

So, let's say that n is 2 and I have 3 items, This is how my items should look like,

-----------
| 1 || 3 |
-----------
| 2 |
-----------

For the same n, with 6 items,

-----------------
| 1 || 3 || 5 |
-----------------
| 2 || 4 || 6 |
-----------------

And so on..

I have tried tinkering it with float: left with no lucks. And now I am kinda learning flex layout, which leads me to stuck.

Please help :) Here's my Fiddle

Note: All my items will have the same width and height.

Upvotes: 1

Views: 133

Answers (1)

Mi-Creativity
Mi-Creativity

Reputation: 9654

Something like this?

jsFiddle 1

.items {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
/* Below this is just styling */

.items {
  background-color: #0f9c8a;
  padding: 4px;
  height: 250px;
  width: 100%;
}
.item {
  width: 100px;
  height: 100px;
  background-color: #6f6ac2;
  border: 1px solid #fff;
  margin: 2px;
  text-align: center;
  line-height: 100px;
}
<div class="items">
  <div class="item">
    Item 1
  </div>
  <div class="item">
    Item 2
  </div>
  <div class="item">
    Item 3
  </div>
  <div class="item">
    Item 4
  </div>
  <div class="item">
    Item 5
  </div>
</div>


Update: since you need to align the .item divs to the left just add align-content:flex-start; to the container .items, like this:

jsFiddle 2

.items {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start;
}
/* Below this is just styling */

.items {
  background-color: #0f9c8a;
  padding: 4px;
  height: 250px;
  width: 1000px;
}
.item {
  width: 100px;
  height: 100px;
  background-color: #6f6ac2;
  border: 1px solid #fff;
  margin: 2px;
  text-align: center;
  line-height: 100px;
}
<div class="items">
  <div class="item">
    Item 1
  </div>
  <div class="item">
    Item 2
  </div>
  <div class="item">
    Item 3
  </div>
  <div class="item">
    Item 4
  </div>
  <div class="item">
    Item 5
  </div>
</div>

Upvotes: 2

Related Questions