Search code examples
jquerycssjquery-masonry

floated divs in 3-a-row grid, middle row with top offset


how do i achieve this as per image attached?

enter image description here

as you can see, i have equal width blocks floated left, but i want the middle row to have a bit of offset compared to the left and right rows.

is it possible just with plain css, flexbox maybe? or do i have to use something like masonry?

i tried applying a top margin to every block in the middle row but this doesnt work:

.block {
 background-color:red;
 height:200px;
 width:33.333%;
 border:1px solid black;
 float:left;
 box-sizing: border-box;
}

.block:nth-child(3n+2) {
 margin-top:10px;
 background:blue;
 color:white;
}

https://jsfiddle.net/oaLh13dL/2/


Solution

  • You can use Flexbox instead of floats.

    .block_wrap {
      display: flex;
      flex-wrap: wrap;
    }
    .block {
      background-color: red;
      height: 200px;
      flex: 0 0 calc(33.333% - 20px);
      border: 1px solid black;
      box-sizing: border-box;
      margin: 0 10px;
    }
    .block:nth-child(3n+2) {
      margin-top: 10px;
      background: blue;
      color: white;
    }
    <div class="block_wrap">
      <div class="block">1</div>
      <div class="block">2</div>
      <div class="block">3</div>
      <div class="block">4</div>
      <div class="block">5</div>
      <div class="block">6</div>
      <div class="block">7</div>
      <div class="block">8</div>
    </div>