0jezca
Last Updated: January 21, 2017
·
43.94K
· peterfrench
711bb352c10800585f54ceb090550ecc

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>

3 Responses
Add your response

20875
0 54wi7wkouj7zdkpdbxey7otdbve9ffgdbjxy7ilze0yfr zwdouf3wlnmnhhuhilkrwj8u71lzrz

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 ·
20876
0 54wi7wkouj7zdkpdbxey7otdbve9ffgdbjxy7ilze0yfr zwdouf3wlnmnhhuhilkrwj8u71lzrz

it work! thanks

over 1 year ago ·
23322
Twitterav normal

Thank you.

over 1 year ago ·