Sticky

ska-theme includes an Alpine.js component for creating a sticky header.

For creating a sticky header, add the x-data="skaSticky" attribute to the element that should stick. That element will receive the .is-sticky class when it is sticky.

Module argumentsTypeScript
interface StickyConfig {
	/** Offset from the top when the element should become sticky. */
	offset?: number
	/** Selector for trigger element used to determine the offset. When used, the `offset` parameter can be used to fine-tune the value, for example `{trigger: '.ska-menu', offset: -5}` will trigger sticky 5px above the `.ska-menu` element. */
	trigger?: string
	/** Add `--sticky-min-h` and `--sticky-y` inline CSS variables that can be used to produce a smooth height change when the menu height is not the same while being sticky and not. */
	smoothHeight?: boolean // Defaults to false
	/** Watch for `x-trap.noscroll` adding `overflow:hidden;padding-right:npx` to document and apply the padding to sticky element as well to prevent layout shift. */
	watchNoScroll?: boolean // Defaults to true
}

Arguments can be specified like this: x-data="skaSticky({offset: 128})", x-data="skaSticky({trigger: '.ska-menu', offset: -10})"

When making a sticky header, it’s a good idea to give it a fixed height and wrap it in an element that has the same height. For example a wrapper element for a header with 4rem height can use Tailwind classes [--header-height:var(spacing-16)] h-[--header-height] *:h-[--header-height]. Now changing the --header-height variable will change both the wrapper and the header height.

The sticky header should have Tailwind classes for when the .is-sticky class is added to the element, such as:

/** When using `[&.is-sticky]:` selector */
fixed top-(--ska-wp-admin-bar-height) right-0 left-0 min-h-(--sticky-min-h)
/** Without using a selector. */
[&.is-sticky]:fixed [&.is-sticky]:top-(--ska-wp-admin-bar-height) [&.is-sticky]:right-0 [&.is-sticky]:left-0 [&.is-sticky]:min-h-(--sticky-min-h)

but appearance styles can be changed as well, such as:

shadow-lg backdrop-blur-sm

To change any element deeper in the header based on the header’s “sticky” state, this variant can be used:

[.is-sticky_&]

Sticky header example

Scroll down to make the example stick.