1

The adjacent selector is nice to use to get margin between elements in for example a card design. But how do you keep the same design when using flexbox when making responsive elements. This seems to remove the margin only of the first element and not on the first element on every line. Are there any elegant solutions for this problem? Ideally the 8 elements would look the same when they are all on one line or 4 lines.

.container {
  display: flex;
  flex-wrap: wrap;
}

.card {
  height: 250px;
  width: 250px;
  background-color: blue;
}

.card+.card {
  margin-left: 10px;
}
<div class="container">
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
</div>

Code also on jsbin: https://jsbin.com/cusekumiza

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Anders
  • 9,988
  • 7
  • 30
  • 36

1 Answers1

1

You can use the way that the most of responsive framework solve this case: use a "row" container to "compensate" left and right margin, by setting them negative, like this:

  .container {
      display: flex;
      flex-wrap: wrap;
      //this will "cancel" the margin on the left an right side
      margin-left:-10px;
      margin-right:-10px;
      justify-content:space-between; //this is to justify block on left and right side 
     //but it will set auto margin between block, don't set if you don't care of the right side
    }
    .card {
      height: 250px;
      width: 250px;
      background-color: blue;
      margin: 10px; // you appli normally the margin for your block
    } 

Here is my js Bin : https://jsbin.com/buwezudiju/1/edit?html,output

Cawet
  • 254
  • 2
  • 12