What is Affix in Bootstrap?

Overview

The Affix plugin allows you to affix (lock) an element to a specific region on the page.

We may have visited a website where the navigation bar or the social handles of the website floats, or stick to a particular position even when we scroll past it. Bootstrap Affix is only triggered when we scroll past the navigation bar or any group it is applied to.

We can make it float at any position on our screen when visitors to our website scroll up. Let us see an example of this.

Example

Bootstrap affix

Explanation

We can visit this shot to learn about the navigation bar.

There are two major attributes we use to apply the affixation to a <nav> element (navigation bar):

  1. data-spy="affix": This attribute is responsible for placing the navigation bar in a fixed position after we scroll. It is a Bootstrap plugin.

  2. data-offset-top="195": This attribute determines how far the user will scroll past the navigation bar before it is triggered. Without this attribute, the affix is triggered automatically after the user scrolls past the navigation bar.

In the code widget above, that <nav> wraps <ul> and <li>. The data-offset-top="195" attribute sets the position of the navigation. So, to affix <nav>, we just add data-spy="affix" and data-offset-top="195". The "195" number is not constant, and can be changed to fits our website.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources