Could we help you? Please click the banners. We are young and desperately need the money
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.
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.
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: