Bootstrap 3 - Column top margin on smaller screens
I needed something similar and following is the solution I came up with. Documenting it for future readers (and myself)
$res-list: (xs: (0px, 767px), sm: (768px, 991px), md: (992px, 1199px), lg: (1200px, 9999px));
$dir-list: (t: top, r: right, b: bottom, l: left);
@for $r from 1 through 10{
@each $res-abbr, $res-vals in $res-list{
@media (min-width: nth($res-vals, 1)) and (max-width: nth($res-vals, 2)) {
@each $dir-abbr, $dir-name in $dir-list{
$x: $r * 5;
.m#{$dir-abbr}-#{$res-abbr}-#{$x}{
margin-#{$dir-name}: #{$x}px;
}
.m#{$dir-abbr}-#{$res-abbr}-#{$r}p{
margin-#{$dir-name}: #{$r}unquote('%');
}
}
}
}
}
This SASS code generates classes along the lines of following
@media (min-width: 0px) and (max-width: 767px) {
.mt-xs-5 { margin-top: 5px; }
.mt-xs-1p { margin-top: 1%; }
.mr-xs-5 { margin-right: 5px; }
.mr-xs-1p { margin-right: 1%; }
.mb-xs-5 { margin-bottom: 5px; }
.mb-xs-1p { margin-bottom: 1%; }
.ml-xs-5 { margin-left: 5px; }
.ml-xs-1p { margin-left: 1%; }
}
So the content editor can use .mt-xs-10
to apply margin-top: 10px
to given element on extra-small
screen.
I hope it helps somebody.
You can use a media query for whenever you want the top margin..
@media (max-width: 767px) {
.col-xs-6 {
margin-top:20px;
}
}
http://www.bootply.com/126007
P.S. - There is nothing wrong with having the total of .col-*
in a .row
exceeding 12 (ie: http://getbootstrap.com/css/#grid-example-mixed). It simply causes a wrap. There are several examples in the docs that use this technique. It's generally not ideal for nested rows.
This is an old post but below is a clean solution.
[class*="col-"] {
margin-bottom: 15px;
}
This works well for some situations but it adds extra, unnecessary margin when it's not needed.
To solve this, we can create a new css class that applies top margin to columns when they get stacked. I create a class named .row-grid
.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;
}
}
I use this simple and clean solution:
.row { margin-top: -15px; }
.row > div { margin-top: 15px; }
In that manner, every <div class='col-*-*'>
has 15px margin on top, except those on the first row (or, on mobile, except the one on the top).