LoginSignup
2
0

More than 3 years have passed since last update.

ヘッダーを途中から固定させたい!

Last updated at Posted at 2020-03-28

概要

ポートフォリオサイト作成時、
スクロールしてヘッダーを途中から固定させたいと思い実装していたのですが、
なかなか上手くいかなかったので備忘録としてまとめます。

おかしなところあったらご指摘ください・・・

条件

ビューはHamlで記載
jQuery導入済み

Html

スクロールしてtop-visualを過ぎた後にheaderが固定されるイメージです。

index.html.haml
.top
  .top-visual
    .top-visual__movie-area
      = image_tag "top-image"
  .header
    .header__line
      .header__nav-bar
        .header__container
          .header__title
            My portfolio
          .header__nav-area
            %ul.header__nav-lists
              %li.header__nav-item
                = link_to "HOME", "#"
              %li.header__nav-item
                = link_to "ABOUT", "#"
              %li.header__nav-item
                = link_to "WORKS", "#"
              %li.header__nav-item
                = link_to "SERVISE", "#"
              %li.header__nav-item
                = link_to "CONTACT", "#"
  .main
    .main-content

CSS

index.scss
.fixed {
  // 本来であれば「position: fixed」の「!important」は不要です。
  // 上手く固定されないときは試してみてください。
  position: fixed !important;
  top: 0;
  left: 0;
  z-index: 2;
  width: 100%;
  color: #fff;
  margin-bottom: 100px;
  background-color: #1A1A1A;
}

.header{
  // position: absoluteを指定しないと固定させるときにガクンとビューが崩れます。
  position: absolute;
  height: 50px;
  width: 100%;
}

jQuery

index.js
$(function() {
    var $win = $(window),
        $main = $('main'),
        $nav = $('header'),
        navHeight = $nav.outerHeight(),
        navPos = $nav.offset().top,
        fixedClass = 'fixed';

    $win.on('load scroll', function() {
      var value = $(this).scrollTop();
      if ( value > navPos ) {
        $nav.addClass(fixedClass);
        $main.css('margin-top', navHeight);
      } else {
        $nav.removeClass(fixedClass);
        $main.css('margin-top', '0');
      }
    });
  });

完成

Image from Gyazo

CSSとJSは奥が深い・・・!引き続き精進してまいります・・・!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0