How to create a blog layout using CSS grid

Creating grid layouts used to be a real pain in the keester…but no more!

It used to be that coding a grid layout for things like a blog archive involved writing a lot of CSS and in hindsight feels pretty hacky.

Float this div left, add margins, add min-height and overflow. But what about snippets with longer titles breaking rows? And what about responsive?

CSS grid takes care of these concerns with relative ease.

Skip right to the demo if you just want to get right to the results.

Steps for creating your grid layout

Here’s a screenshot (desktop view) of what we’ll be creating:

css grid example screenshot

The grid itself is generated by using the following:

.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr;
  grid-column-gap: 40px;
  grid-row-gap: 40px;
  justify-items: stretch;
  align-items: stretch;

.grid-item {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  overflow: hidden;

From there we add styling for the article snippets that will be displayed inside the grid:

article {
  position: relative;
  text-align: center;
  background: #fff;
  border-radius: 4px;
  transition: all 0.15s ease-in-out;
  overflow: hidden;

The HTML is basically adding each article wrapped in the grid container:

<!-- begin grid container -->
<div class="grid-container">
      <img src="" alt="#">
    <h2>Lorem ipsum dolor sit amet consectetur adipiscing elit</h2>
    <span class="post-date">
      Wednesday, April 4, 1973
    <p><a href="#" class="more-link">Read the article »</a></p>

  <!-- paste additional snippets here, 4 per row will be displayed -->

</div><!-- # grid container -->

Most of this solution is responsive out of the gate, but when you inspect the CSS in the pen you’ll notice that I did reset the number of snippets displayed per row based on two adaptive breakpoints, as in the following example:

/* for smartphones, displays two per row */
@media only screen
and (max-width : 1024px) {

  .grid-container {
    grid-template-columns: 1fr 1fr;
}/* end media query */

/* for smartphones, displays one per row */
@media only screen
and (max-width : 768px) {
  .grid-container {
    grid-template-columns: 1fr;
}/* end media query */

Demo and code

You’ll notice I’ve added some additional styling for cosmetic purposes but the essentials explained above is enough to get you started.

View the pen so you can see the larger version or check out the embed below for a live example and to snag the markup and CSS for your own project:

Have fun!

Archived under:
This site uses cookies to collect basic info to help improve your experience. Read my Privacy Policy Accept