htmlcssbootstrap-4twitter-bootstrap-4spacing

Add spacing between vertically stacked columns in Bootstrap 4


Unfortunately, there doesn't seem to be a good way to manage vertical spacing between columns that transition from a horizontal stack to a vertical stack at certain breakpoints. There does seem to be a solution when a form is involved, but that's not the situation here. I've tried this solution, but it doesn't work when there are multiple columns that wrap in a row.

To illustrate my scenario, here's the structure of my HTML:

<body>

  <div class="container">

    <div class="row">

      <div class="col-md-4">
        col 1
      </div>

      <div class="col-md-4">
        col 2
      </div>

      <div class="col-md-4">
        col 3
      </div>

      <div class="col-md-4">
        col 4
      </div>

      <div class="col-md-4">
        col 5
      </div>

      <div class="col-md-4">
        col 6
      </div>

    </div>

  </div>

</body>

https://jsfiddle.net/b74a3kbs/6/

At medium-device size (md) and above, I'd like there there to be spacing between the two "rows" of columns, but no spacing above the "first row" of 3 columns and none below the "second row" of 3 columns. When the columns stack vertically at below the medium-device size (md), I'd like there to be spacing between each of the columns, but none above the first child and none below the last child.

Ideally, the solution would work regardless of how many columns (e.g., 3, 5, 6, 12) are contained within the row.


Solution

  • Here's how I ended up making this work:

    .row [class*="col-"] { 
       @extend .mb-4;
    
       &:last-child {
         @extend .mb-0;
       }
    
       @extend .mb-md-5;
    
       &:nth-last-of-type(1),
       &:nth-last-of-type(2),
       &:nth-last-of-type(3) {
         @extend .mb-md-0;
       }
    }