Blog

Autospace Bootstrap columns on small screens

A little trick I have been using in pretty much every design I worked on that was based on Bootstrap is to automatically add a margin between grid columns when they break/collapse, i.e. are displayed vertically instead of horizontally.

The code looks like this:

[class^="col-sm-"],
[class*=" col-sm-"] {

  @media (max-width: $screen-xs-max) {

    & + & {
      margin-top: 40px;
    }
  }
}

(replace $screen-xs-max with @screen-xs-max if you're using LESS instead of Sass)

This snippet basically says that, when the screen is max. $screen-xs-max (767px) wide, any "small column" (i.e., any element with a class starting with col-sm-), that follows another small column, should have a top margin of 40px.

This is very similar to the "lobotomized owl selector" * + * which lets you apply a top margin (or any other style) to any element that is preceded by another element.

Hope you find this quick tip useful!

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!