Last Updated: June 27, 2023
·
154.3K
· peterfrench

Vertical Spacing for Bootstrap Columns

Problem

While using Twitter Bootstrap, I ran into some vertical spacing issues when bootstrap's columns started to stack. For example, lets take a look at a 3 column layout for medium sized screens.

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

If a tablet or phone viewed that layout, all the columns would be stacked but each column might be directly touching the previous column.

A simple solution to this is to add a bottom margin to every column:

[class*="col-"] {
    margin-bottom: 15px;
}

This works well for some situations but it adds extra, unnecessary margin when it's not needed.

Solution

To solve this, we can create a new css class that applies top margin to columns when they get stacked:

.row.row-grid [class*="col-"] + [class*="col-"] {
    margin-top: 15px;
}

@media (min-width: 1200px) {
    .row.row-grid [class*="col-lg-"] + [class*="col-lg-"] {
        margin-top: 0;
    }
}
@media (min-width: 992px) {
    .row.row-grid [class*="col-md-"] + [class*="col-md-"] {
        margin-top: 0;
    }
}
@media (min-width: 768px) {
    .row.row-grid [class*="col-sm-"] + [class*="col-sm-"] {
        margin-top: 0;
    }
}

The row-grid class applies a top margin to columns that have a preceding column. The media queries then remove the top margin when it isn't needed.

On a related note, if you wanted to add vertical spacing between your rows add this line to your css:

.row-grid + .row-grid {
    margin-top: 15px;
}

Usage

Simply add the row-grid class to rows where you want to enable the vertical column spacing.

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

4 Responses
Add your response

Thank You! been looking for this solution. i have a question will it work on this layout:

.row >
.col-xs-12 .row-grid >
.col-md-4
.col-md-4
.col-md-4

i decided to add another col-xs-12 so i can have a 30px spacing on the sides when it comes to mobile. will it work?

over 1 year ago ·

it work! thanks

over 1 year ago ·

Thank you.

over 1 year ago ·

With Bootstrap 4 and mixins you can achieve it like this. I use my-auto in my columns so your method didn't work well for me as I want my content vertically centred in rows.

@include media-breakpoint-down(xs) {
.row.row-grid [class="col-"]+[class="col-"] {
margin-top: 15px !important;
}
}

over 1 year ago ·
  NODES
Community 1
iOS 2
Javascript 5
node.js 1
Note 1
os 7
twitter 4
web 2