Change Number of Div Elements in Row Based on Screen Size with Bootstrap

Viewed 4346

Is it possible to have different numbers of <div> elements depending on screen size with Bootstrap?

For example, 4 columns per row on desktops.

+-----------+-----------+-----------+-----------+
| .col-md-3 | .col-md-3 | .col-md-3 | .col-md-3 |
+-----------+-----------+-----------+-----------+
| .col-md-3 | .col-md-3 | .col-md-3 | .col-md-3 |
+-----------+-----------+-----------+-----------+

Then instead of having each column span 100% on tablets and phones, have 3 columns per row on tablets. Pushing columns over 12 to the next row, like below.

+-----------+-----------+-----------+
| .col-sm-4 | .col-sm-4 | .col-sm-4 |
+-----------+-----------+-----------+
| .col-sm-4 | .col-sm-4 | .col-sm-4 |
+-----------+-----------+-----------+
| .col-sm-4 | .col-sm-4 |
+-----------+-----------+

I found Bootstrap's responsive utilities, where I can hide or show columns only for certain screen sizes. This would mean I have to repeat tons of the columns however (see snippet below), so I was hoping there would be a cleaner solution.

<!DOCTYPE html>
<html lang="en">
<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section class="container">
<div class="row">
    <div class="col-md-3 col-sm-4">
      <p>1</p>
    </div>
    <div class="col-md-3 col-sm-4">
      <p>2</p>
    </div>
    <div class="col-md-3 col-sm-4">
      <p>3</p>
    </div>
    <div class="col-md-3 hidden-sm">
      <p>4</p>
    </div>
</div>
<div class="row">
    <div class="hidden-md visible-sm-4">
      <p>4</p>
    </div>
    <div class="col-md-3 col-sm-4">
      <p>5</p>
    </div>
    <div class="col-md-3 col-sm-4">
      <p>6</p>
    </div>
    <div class="col-md-3 hidden-sm">
      <p>7</p>
    </div>
    <div class="col-md-3 hidden-sm">
      <p>8</p>
    </div>
</div>
<div class="row">
    <div class="hidden-md visible-sm-4">
      <p>7</p>
    </div>
    <div class="hidden-md visible-sm-4">
      <p>8</p>
    </div>
</div>
</section>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

As far as I am aware, you cannot leave out the containing .row div. It would be nice to be able to just put class="col-md-3 col-sm-4 col-xs-6" for all the elements and let bootstrap take however many <div>s to add up to 12. So 4 on medium screens, 3 on small screens, and 2 on extra small.

1 Answers
Related