Quantcast
Channel: CSS — SitePoint
Viewing all articles
Browse latest Browse all 15

Quick Tip: How to Align Column Rows with CSS Subgrid

$
0
0

In this quick tip, we'll look at how to use the subgrid feature of CSS Grid to align the content of boxes that sit side by side.

Note: before delving into subgrid, it's important to understand the basics of Grid layout. If you're new to Grid, or you need a refresher, check out our beginner's guide to CSS Grid.

The Problem

The image below shows three boxes in a row. They have different amounts of content, but they're all the same height thanks to Grid layout.

Columns whose content doesn't align nicely

However, the components within each box don't align with each other, which doesn't look so nice, and there's nothing Grid can do about that. As far as Grid is concerned, there's just one row of boxes, and it doesn't offer a way to align the content they contain into rows. But by using subgrid, we can get the result shown below.

The components within the columns are now aligned

Let's dive into how to use Grid and subgrid to get this result.

Step 1: Setup

Here's the basic HTML for our demo:

<article>
  <section></section>
  <section></section>
  <section></section>
</article>

We have and <article> wrapper containing three <section> elements. The <article> has the following CSS:

article {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

This CSS causes the <section> elements to be arranged in three columns.

Each <section> contains an <h1>, a <ul> and a <div>:

<section>
  <h1></h1>
  <ul></ul>
  <div></div>
</section>

At this stage, each column in the grid is actually the same height, but not each column is full of content, as shown below.

The grid columns are the same height, but the content doesn't stretch the full height of some columns

There's a different amount of content in each column, so they don't appear to be the same height.

The post Quick Tip: How to Align Column Rows with CSS Subgrid appeared first on SitePoint.


Viewing all articles
Browse latest Browse all 15

Trending Articles