Bootstrap Affix

The Affix Plugin

The Affix plugin is used when you want some element to stay fixed or stuck on some area of the page.

This is usually done with the social icon buttons of your website so that they are locked as you scroll up or down on the page.

You can also make your navbar fixed on the page so that its position is locked while you scroll through the page.

Creating an Bootstrap Affixed Navibar

You need to use the data-spy= “affix” attribute for this. Check the code below for example

Same can be done with a vertical affixed navigation menu. See the code below for example:

Let us now try to understand the working of the affix elements.

There are three major classes you need to know to undersand affix:

  • .affix
  • .affix-top
  • .affix-bottom

All these classes represent a particular state each. See the description below for better understanding:

The .affix-top or .affix-bottom class indicates that the element is at the top-most or bottom-most position.

So, for now CSS positioning is not required.

Once you scroll past the affixed element the actual affixing is triggered. Now the .affix-top or .affix-bottom class is replaced with the .affix class.

This is also the point where you need to add the CSS top or bottom property.

If you have defined a bottom offset, the .affix class will be replaced by .affix-bottom once you scroll past it.

The CSS property, position: absolute will help you with this.

You can also use the Affix and Scrollspy plugins together:

Bootstrap Horizontal Menu (Navbar)

The code below illustrates the horizontal navbar to be affixed to the page.

This is done when you need the navbar to be accessible throughout the page

Bootstrap Vertical Menu (Sidenav)

The code below illustrates the Vertical menu affixed to the page.

This is done usually when the a part or whole of the menu needs to be accessible throughout the page.

Bootstrap Via data-* Attributes

For the affix plugin, there are three data* attributes used that are

  • data-spy: To set element as affix
  • data-offset-top: To set the top position of the affixed element
  • data-offset-bottom: To set the bottom position of the affixed element

Bootstrap Affix Events

Here’s a list of all the affix events that you need to know:

  • bs.affix: Even just before the element position is going to be affixed. The .affix-top class is now about to be replace with .affix
  • bs.affix: Event of the fixed positioning of the affixed element. So, the .affix class has now replaced the .affix-top
  • affixed-top.bs.affix: Event of the top element returning to its original postion. The .affix is again replaced with the affix-top class.
  • affixed-bottom.bs.affix: Event before and after the bottom element has returned to its original position. The .affix class is replaced with the .affix-bottom class.