見出し画像

スクロールすると高さが可変するヘッダーの作り方

スクロールすると高さが可変するヘッダーの作り方を自分用にまとめてみました。

-完成DEMO-

HTML

<header id="header">
  <ul>
    <li>menu1</li>
    <li>menu2</li>
    <li>menu3</li>
  </ul>  
</header>
<div class="hero">
  <img src="https://dl.easyuploader.cloud/20211227210535_324a487a.jpg" alt="hero">
</div>
<div id="contents">
  <p>contents</p>
</div>
<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  {
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  /* スクロールしても他のコンテンツの下にならないようにする */
  z-index: 10;
  background-color: #262421 ;
  transition: all 0.8s ease;
}

/* スクロールして「scroll-navクラス」がついたときのヘッダーデザイン */
 #header .scroll-nav {
  /* 高さを低くする */
  height: 70px;
  /* 背景を白にする */
  background: #fff ;
  /* コンテンツの背景が白でもナビゲーションだと分かりやすいように影をつける */
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}

/* 「scroll-navクラス」がヘッダーについたときに、ナビゲーションの文字色を変更する */
 #header .scroll-nav ul li {
  color: #333333 ;
}
 #header  ul {
  display: flex;
}
 #header  li {
  color: #fff ;
  font-weight: 600;
  padding: 0 2.5rem;
}
 #header .transform { 
width: 100%;
height: 60px;
}
.hero img {
  width: 100%;
  min-height: 100vh;
  vertical-align: bottom;
}
/*---------------------------
        
         2. contents  

---------------------------*/
 #contents  {
  height: 800px;
  display:flex;
  justify-content: center;
  align-items: center;
  background-color: #F8F7F5 ;  
}
 #contents  p {
  font-size: 1.875rem;
  color: #333333 ;
}
/*---------------------------
        
         3. footer  

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

JS

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


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