Menü schliessen
Created: November 12th 2024
Last updated: November 12th 2024
Categories: Common Web Development,  CSS
Author: Tim Fürer

CSS: How to horizontally align child elements inside grid items

Tags:  CSS,  guide,  HTML
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In this article, we'll discuss subgrid's capabilities to align child elements across grid items on the same row.

Subgrid is Baseline 2023 and available across major browsers since September 2023, which makes up more than 90% of tracked browser installations.


The Problem

Imagine you have some panes in a grid row. Part of their content, namely their text, is variable. Since some panes' texts are shorter and some are longer, each pane ends up sized differently from the other.

The described scenario may like look something along the lines of this:
As you can see, the final element within each of the panes, which happens to be a button, isn't always at the bottom. It appears to float in the "air", and this may be undesirable. You may want to align certain child elements, such as these buttons, with their placement inside other panes.

 


The Solution: Subgrid

To effectively use subgrid for our alignment purposes, we first need to make sure our HTML structure is appropriate. Our goal is to align the buttons with one another, thus I've structured the panes like so:

<div class="pane">
    <div>
        <h2>
            Title
        </h2>
        
        <p>
            Text.
        </p>
    </div>

    <button>
        Button
    </button>
</div>

Inside the pane, there are essentially two rows: the first represents the title and text, the second is the button. Applying subgrid to the panes allows us to align those rows:

.pane {
    display: grid;
    grid-template-rows: subgrid;
    grid-row: auto / span 2;
}

By setting the pane's grid template to "subgrid", we are telling it to reference the other panes in the grid for sizing its rows. We also define how many rows a pane contains (in this case 2).

The result is that the rows are now nicely aligned and our panes look like this: