nikjohn nikjohn - 12 days ago 5
CSS Question

How to convert Bootstrap rows to columns by Viewport size

I have a layout that looks like this on

lg
and
sm
:

enter image description here

I want the same divs to be rows on
lg
and cols on
sm
. Is there a way to do this without having completely different divs? The solution I came up with is:

.box-a.row.visible-lg.hidden-sm
.box-b.row.visible-lg.hidden-sm
.box-c.row.visible-lg.hidden-sm

.box-a.col-sm-4.visible-sm.hidden-lg
.box-b.col-sm-4.visible-sm.hidden-lg
.box-c.col-sm-4.visible-sm.hidden-lg


But this, like I said, involves redundant code. Is there a way to do this in a cleaner DRYer manner?

Answer

You can put all columns in a .row and, because bootstrap grid is composable, each column can have both col-sm-4 and col-lg-12 classes.

The grid structure is:

  1. namespace: col
  2. screenSize: xs|sm|md|lg
  3. colSpan: 1-12

So, you are able to have any mix of them:

  • When screen is LG (to UP) colspan is 12: col-lg-12
  • When screen is SM (to UP) colspan is 4: col-sm-4

@import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css";


.box {
  height: 50px;
  background: lightcoral;
  border: 1px solid green;
  margin: 5px 0;
}
<section class="container">
  <div class="row">
    
    
    <div class="col-sm-4 col-lg-12">
      <div class="box"></div>
    </div>
    
    <div class="col-sm-4 col-lg-12">
      <div class="box"></div>
    </div>
    
    <div class="col-sm-4 col-lg-12">
      <div class="box"></div>
    </div>

  </div>
</section>

PS: As of bootstrap works, if a DIV has a class visible-lg that div will be shown only at LG sizes, so, adding a hidden-sm class isn't necessary: .box-a.row.visible-lg.hidden-sm => .box-a.row.visible-lg.

Comments