見出し画像

スクロールすると下線が表示されるヘッダーの作り方

スクロールすると下線が表示されるヘッダーの作り方を自分用にまとめてみました。

-完成DEMO-

HTML

<header id="header">
  <section>
    <div class="header-sp">
      <h1 class="site-logo">
        <a href="#"><img src="https://dl.easyuploader.cloud/20220130202634_77717844.svg" alt="#"></a>
      </h1>
  </section>    
</header>
<main>
  <div class="main-wrapper">
    <p>content</p>
  </div>
</main>
<footer id="footer">
  <p>footer</p>
</footer>

CSS

/*---------------------------
        
      0.common setting   

---------------------------*/
* {
  margin: 0;
  padding: 0;
}

html {
  font-size: 100%;
}

body {
  font-family: 'Noto Sans JP', sans-serif;
  font-size: 1rem;
  color: #333333 ;
  line-height: 1.5;
}

ul {
  list-style: none;
}
/*---------------------------
        
         1. header   

---------------------------*/
.header-sp {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  /*paddingとborderを幅と高さに含める*/
  box-sizing: border-box;
  background-color: #262421 ;
  width: 100%;
  height: 60px;
  z-index: 9998;
  border-bottom: 1px solid #262421 ;
  /* 下線の色が変わる時間を調整 */
  transition: all 1s ease;
}

/* スクロールして「scroll-navクラス」がついたときのヘッダーデザイン */
.header-sp.scroll-nav {
  border-bottom: 1px solid red;
}

/* line-heightにh1タグの高さよりも小さい値「0」を指定することで、h1タグの上下の余白が消えるため、ロゴ画像の高さと揃う */
.site-logo {
  display: inline-block;
  line-height: 0;
}

/* aタグのリンク範囲を親要素のサイズに広げる */
.site-logo a {
  display: block;
}

.site-logo img {
  width: 200px;
}

/*---------------------------
        
          2. main   

---------------------------*/
.main-wrapper {
  height: 600px;
  background-color: #F8F7F5 ;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main-wrapper p {
  font-size: 5rem;
}
/*---------------------------
        
          3. footer   

---------------------------*/
 #footer  {
  height: 600px;
  background-color: #333333 ;
  display: flex;
  justify-content: center;
  align-items: center; 
}
 #footer  p {
  font-size: 5rem;
  color: #fff ;
}

JS

window.addEventListener("scroll", function () {
  // ヘッダーを変数の中に格納する
  const header = document.querySelector(".header-sp");
  // 50px以上スクロールしたらヘッダーに「scroll-nav」クラスをつける
  header.classList.toggle("scroll-nav", window.scrollY > 50);
});

この記事が気に入ったらサポートをしてみませんか?