Gjert Ingar Gjersund Gjert Ingar Gjersund - 6 months ago 7
CSS Question

Responsive div columns where column items get shifted on screen resize

I have three columns called

<div class="pageColumnOneThird">
.

Inside each column I fetch images and posts using PHP where the newest item gets placed in the
top left column
and the next one in the
top middle column
and the third one in the
top right column
before it goes back to the
left column
again.

Now I am trying to make this responsive, so that when two columns are displayed, the placement of each image/post are changed.

example: When there are only two columns side-by-side I need the first row of items to be element 1 and 2. Then the second row has to be element 3 and 4.

Is there any way to do this using CSS?

If not, is there any fast jQuery code that can do this for me?

Code

<!-- FIRST COLUMN -->
<div class="pageColumnOneThird">
<div class="itemWrap">Element 1</div>
<div class="itemWrap">Element 4</div>
<div class="itemWrap">Element 7</div>
</div>
<!-- SECOND COLUMN -->
<div class="pageColumnOneThird">
<div class="itemWrap">Element 2</div>
<div class="itemWrap">Element 5</div>
<div class="itemWrap">Element 8</div>
</div>
<!-- THIRD COLUMN -->
<div class="pageColumnOneThird">
<div class="itemWrap">Element 3</div>
<div class="itemWrap">Element 6</div>
<div class="itemWrap">Element 9</div>
</div>


Heres a jsfiddle as well.

Answer

you can simply use one wrapper, and then just use @media queries

.pageColumnOneThird {
  font-size: 0;
}
.itemWrap {
  background-color: #AEAEAE;
  margin: 2px 0;
  width: 33.3%;
  padding: 0 1px;
  height: auto;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  display: inline-block;
  font-size: 16px
}
@media (max-width: 768px) {
  .itemWrap {
    width: 50%
  }
}
@media (max-width: 480px) {
  .itemWrap {
    width: 100%
  }
}
<div class="pageColumnOneThird">
  <div class="itemWrap">Element 1</div>
  <div class="itemWrap">Element 2</div>
  <div class="itemWrap">Element 3</div>
  <div class="itemWrap">Element 4</div>
  <div class="itemWrap">Element 5</div>
  <div class="itemWrap">Element 6</div>
  <div class="itemWrap">Element 7</div>
  <div class="itemWrap">Element 8</div>
  <div class="itemWrap">Element 9</div>
</div>

EDIT Based on OP comment:

This is not what I am looking for as I need to be allowed different heights on each item element, but maintain equal margin WITHOUT adding empty space in the elements. Thats why I need to use three separate columns. Found a picture of what I need https://prod-foundation-forum.s3.amazonaws.com/uploads/part/part_image/93067/illustration.jpg

For that type of layout the best thing for you is masonry

Comments