CSS

Establish Vertical Rhythm with CSS Grid and `grid-auto-rows`

Achieve consistent vertical rhythm in your web layouts by aligning elements to an implicit grid baseline using `grid-auto-rows` and a defined line height for improved readability.

body {
    --base-line-height: 24px;
    font-family: sans-serif;
    line-height: var(--base-line-height);
    margin: 0;
}

.container-with-rhythm {
    display: grid;
    grid-template-columns: 1fr;
    grid-auto-rows: var(--base-line-height); /* Each row is one line height */
    gap: 0; /* No explicit gap, rhythm handled by grid */
    border: 1px dashed #ccc;
    padding: var(--base-line-height); /* Padding also aligns to rhythm */
}

.item {
    background-color: #f0f0f0;
    margin-bottom: var(--base-line-height); /* Use margin to align elements */
    padding: calc(var(--base-line-height) / 2); /* Half line height padding */
}

h2 {
    font-size: calc(2 * var(--base-line-height));
    line-height: calc(2 * var(--base-line-height));
    margin-top: var(--base-line-height);
    margin-bottom: var(--base-line-height);
}

p {
    margin-bottom: var(--base-line-height);
}

/* Example to demonstrate how it stacks */
.container-with-rhythm .item:nth-child(odd) {
    background-color: #e0e0e0;
}

<!-- HTML Structure -->
<div class="container-with-rhythm">
    <h2>Section Title</h2>
    <div class="item">
        <p>This is a paragraph inside an item. It should align to the baseline grid established by `grid-auto-rows`. This helps maintain consistent spacing and readability across the layout.</p>
    </div>
    <div class="item">
        <p>Another item with content. Notice how the spacing between elements and the overall alignment respects the defined vertical rhythm, thanks to CSS Grid.</p>
        <p>Even multiple paragraphs within an item will try to adhere to the rhythm, though nested elements need careful attention to their own line-heights and margins.</p>
    </div>
    <p>A standalone paragraph, also respecting the rhythm.</p>
</div>
How it works: This snippet demonstrates how to establish a vertical rhythm in your layout using CSS Grid's `grid-auto-rows`. By defining a `--base-line-height` custom property and setting `grid-auto-rows` to this value, every implicit grid row will be exactly one line-height tall. This helps align text baselines and block elements consistently. Elements within the grid should then adjust their `margin-top`, `margin-bottom`, `padding-top`, and `padding-bottom` to be multiples or fractions of the base line height to perfectly snap into this rhythm, creating a more harmonious and readable design.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs