Skip to main content

Archive

Show more

Foundation CSS Sticky

Foundation CSS Sticky

The Foundation CSS Sticky component allows you to create elements that stick to the top or bottom of the viewport as the user scrolls down or up the page. This is useful for creating navigation menus, headers, or other UI elements that should remain visible at all times.


1. Basic Usage

To create a sticky element, add the data-sticky attribute to the target element. By default, the element will stick to the top of the viewport when scrolled past.

Example markup for basic usage:

<div class="sticky" data-sticky data-options="marginTop:0;">
  <h2>Sticky Header</h2>
</div>

In this example, the <div> with the class sticky becomes sticky, and the sticky behavior is applied with default options.


2. Options

The Sticky component provides options for customizing the sticky behavior, such as setting the top or bottom offset, specifying the sticky container, or toggling the sticky element's visibility on scroll.

Example markup with options:

<div class="sticky" data-sticky data-options="marginTop:0; stickyOn: large;">
  <h2>Sticky Header</h2>
</div>

In this example, the sticky element will stick to the top of the viewport when the screen size is large, and the top margin is set to 0 pixels.


3. JavaScript Initialization

If you prefer to initialize the Sticky component programmatically using JavaScript, you can do so using the Foundation.Sticky plugin. This allows for more advanced customization and dynamic control over sticky elements.

Example JavaScript initialization:

import { Sticky } from 'foundation-sticky';

// Initialize sticky elements with custom options
const sticky = new Sticky('[data-sticky]', {
  marginTop: 0,
  stickyOn: 'large'
});

In this example, sticky elements are initialized with the same customization options as described earlier.


Conclusion

The Foundation CSS Sticky component provides a simple yet powerful way to create sticky elements that remain visible as the user scrolls down the page. Whether you're building a navigation bar, header, or any other UI element that needs to stay in view, the Sticky component enhances the usability and navigation experience of your website.

Comments