Overview
The ScrollToTop component provides a floating button that appears when users scroll down the page, allowing them to quickly return to the top. The button is hidden by default and shows dynamically based on scroll position.Component code
src/components/ScrollToTop.astro
Features
Fixed positioning
The button uses fixed positioning (!fixed) in the bottom-right corner:
- Bottom: 5 units (
bottom-5) - Right: 5 units (
end-5)
Hidden by default
The button starts with thehidden class and is revealed via JavaScript when the user scrolls down.
Visual design
rounded-full - Circular button- Default:
bg-amber-600 - Hover:
hover:bg-amber-700 - Focus:
focus:bg-amber-700 - Active:
active:bg-amber-800
- Default:
shadow-md - Hover:
hover:shadow-lg - Active:
active:shadow-lg
- Upward arrow
- Width: 6 units (24px)
- Stroke width: 3
- Color: White
JavaScript implementation
The button’s show/hide behavior is controlled by JavaScript in the Layout component:src/layouts/Layout.astro (lines 38-42)
Show/hide logic
- Threshold: 20 pixels
- Action when scrollY > 20: Remove
hiddenclass (button appears) - Action when scrollY ≤ 20: Add
hiddenclass (button disappears)
Scroll behavior
- Click action: Scroll to top of page
- Animation: Smooth scroll (
behavior: 'smooth')
Styling details
Button dimensions
- Padding:
p-4(16px on all sides) - The circular shape combined with equal padding creates a perfect circle
Typography
- Font size:
text-xs - Font weight:
font-medium - Text transform:
uppercase - Line height:
leading-tight - Color:
text-white
Transitions
- Duration:
duration-150 - Easing:
ease-in-out - Applies to all state changes (hover, focus, active)
Accessibility
- Focus outline removed:
focus:outline-none focus:ring-0 - Button type explicitly set:
type="button" - Semantic HTML: Uses
<button>element
Ripple effect
The button includes data attributes for Tailwind Elements ripple effect:data-twe-ripple-init- Initializes rippledata-twe-ripple-color="light"- Sets ripple color
The ripple effect requires Tailwind Elements JavaScript library to be initialized. Without it, the button will still function normally but without the ripple animation.
Usage
The ScrollToTop component is imported in the Layout and placed at the page level:src/layouts/Layout.astro
src/pages/index.astro
