I learned Bootstrap earlier this year for a few projects. Mostly because I wanted to use its grid system and template navbar for a few things. And while it did allow me to quickly cut & paste some code, I felt that the grid was a bit cumbersome. So I decided to try and make something simple that I could use for future projects, especially those that just needed a simple grid layout (like a portfolio).

What I came up with was a simple CSS grid using under 30 lines of code that is fully responsive and allows for either a 3 or 4 column max on larger screens.

The first thing I did was to give the container div a class:

  .grid {
  max-width: 900px;
  margin: 0 auto;
}

The max-width setting keeps a nice looking grid even on super wide screens.

Next, I set the "grid" for mobile, so basically just vertically aligning grid items:

  .col-3,
.col-4 {
  width: 90%;
  margin: 1em auto;
  box-sizing: border-box;
}

The items in the grid are given class names of either ".col-3" or ".col-4" depending on if you want to max out at 3 or 4 columns on larger screens. And the "border-box" setting allows the grid to keep its structure whether or not you add borders to your grid items.

The rest is basically done with media queries using percentage widths & margins:

  @media (min-width: 480px) {
  .col-3,
  .col-4 {
    width: 46%;
    float: left;
    margin: 2%;
  }
}

@media (min-width: 768px) {
  .col-3,
  .col-4 {
    width: 30%;
    margin: 1.65%;
  }
}

@media (min-width: 992px) {
  .col-4 {
    width: 23%;
    margin: 1%;
  }
}

The last media query is only needed for a 4 column max setting.

And that's it! Questions and comments are welcome! The CodePen project can be found here and a live link to a working example here.


639 0 0