A quick guide to resizing Bootstrap’s gutter width

bootstrap-grid-postI don’t know about you, but I’m always  finding myself needing to change bootstrap’s default 30px wide gutter all the time. Well, If you ever find yourself needing to do the same, here is a quick guide.

Step 1: Understand how gutters are implemented

If you dig into bootstrap’s CSS code, you will find the gutter width is setup in the row and individual column classes i.e


.col-xs-1, .col-sm-1, .col-md-1 ...{more columns} {
  padding-right: 15px;
  padding-left: 15px;
}

.row {
  margin-right: -15px;
  margin-left: -15px;
}

From the code, you can see that the gutter value is set as a pair of  left and right pads, each with a value of 15px. These add up to 30px when the columns are floated next to each other. The parent row then uses negative margins to cancel the left and right pads on the first and last columns. Comprende?

Step 2: Constructing your own gutter classes

Let’s say we wanted custom gutters of 20px, 10px and 0px. Using bootstrap’s method, we would halve each of these gutters and use that value in our pads and negative margins. Our new classes would look as follows


// 20px gutter
.gutter-20.row {
  margin-right: -10px;
  margin-left: -10px;
}
.gutter-20 > [class^="col-"], .gutter-20 > [class^=" col-"] {
  padding-right: 10px;
  padding-left: 10px;
}
// 10px gutter
.gutter-10.row {
  margin-right: -5px;
  margin-left: -5px;
}
.gutter-10 > [class^="col-"], .gutter-10 > [class^=" col-"] {
  padding-right: 5px;
  padding-left: 5px;
}
// 0px gutter
.gutter-0.row {
  margin-right: 0;
  margin-left: 0;
}
.gutter-0 > [class^="col-"], .gutter-0 > [class^=" col-"]{
  padding-right: 0;
  padding-left: 0;
}

If you’ve noticed, we did not type all the column classes as they did in bootstrap’s source. Instead we used a shortcut CSS selector known as the attribute selector. The attribute selector selects HTML elements with the specific attributes or attribute values. In our case we are are using the [attribute="value"] selector is  to select elements with class names that match bootstrap’s column syntax.  The [highlight]^[/highlight] character specifies that the class name can only start with the specified value.

Step 3: Usage

Using your new classes is stupid simple! Whenever you want to change any column’s gutter, you simply add you new classes to it’s parent row and everything works as it should without breaking bootstrap’s grid.

<div class="row gutter-10">
  <div class="col-md-6"></div>

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

Checkout a live demo on Codepen

A live codepen demo can be found here

See the Pen EjGGEK by Arnique Studio (@Arnique) on CodePen.