Tip 10/72

Scroll Margin

Smooth Section Navigation with `scroll-my-*`

When building in-page navigation with anchor links, you can ensure proper spacing between sections by using either the scroll-my-* utility or scroll-py-*. Both methods help create smooth scrolling and prevent sections from being hidden behind fixed elements like sticky headers.

Why Use scroll-my-*

The scroll-my-* utility adds vertical margins outside a scroll container. This is particularly useful for managing scroll behavior when navigating to specific sections via anchor links. It ensures proper spacing, preventing sections from appearing cramped or hidden behind sticky headers.

Example without scroll-my-*

Example with scroll-my-32 Applied to Each Section

<main>
    <section class="h-dvh scroll-my-32 bg-blue-300" id="section-1">
        <h2>Section 1</h2>
    </section>
    <section class="h-dvh scroll-my-32 bg-blue-400" id="section-2">
        <h2>Section 2</h2>
    </section>
    <section class="h-dvh scroll-my-32 bg-blue-500" id="section-3">
        <h2>Section 3</h2>
    </section>
</main>

Alternative: Use scroll-py-* on the <body>

You can achieve similar results by applying the scroll-py-* utility directly to the <body> element. This adds consistent vertical scroll padding across the entire page, ensuring that all sections maintain a buffer for smooth navigation.

<body class="scroll-py-16">
    <main>
        <section class="h-dvh bg-blue-300" id="section-1">
            <h2>Section 1</h2>
        </section>
        <section class="h-dvh bg-blue-400" id="section-2">
            <h2>Section 2</h2>
        </section>
        <section class="h-dvh bg-blue-500" id="section-3">
            <h2>Section 3</h2>
        </section>
    </main>
</body>

By adding scroll-py-* to the <body>, you don’t need to apply scroll-my-* to individual sections, making it a great option for consistent spacing across your entire page.

When to Use Each

  • scroll-my-*: Ideal for fine-tuning individual sections when you need different spacing between specific sections or custom behavior.
  • scroll-py-* on <body>: Best for uniform spacing across all sections, requiring less effort for single-page navigation setups.

Perfect for In-Page Navigation

With scroll-my-* or scroll-py-*, you can ensure seamless navigation for users, especially when sticky headers or precise positioning are part of your layout. These utilities make your design clean and eliminate the need for custom CSS.