29 September 2014

I found a better way to use the bootstrap affix style or any other js library providing effect like this.

The bootstrap documentation is on:

We can easy to set the target distance. When user scroll the page down and reach the target distance the affix event would be triggered and class attribute is changed too.

So we use the class to switch the style. Usually usage is fixed the main menu to window with setting CSS position property to absolute or fixed. But if we directly change original element’s position to absolute or fixed the whole page would reduce the element’s height. The scroll action is not smooth and it doesn’t feels good. Just like jump to some where suddenly.

So here provides the better way to handle this kind of interaction design: Keep the height and change the style of element inside.

Bad Example:

.header
  height: 60px
  &.affix
    position: fixed
    ...

Bad Example Demo http://codepen.io/Oliverl/pen/IvygF

See the Pen IvygF by Oliver - Frontend Developer (@Oliverl) on CodePen.

The Better Way:

.header-wrapper
  height: 60px
  .header
    height: 60px
  &.affix
    .header
      position: fixed
      ...

Solution Demo http://codepen.io/Oliverl/pen/HksKl

See the Pen HksKl by Oliver - Frontend Developer (@Oliverl) on CodePen.