본문 바로가기
Coding/HTML & CSS

[Html & CSS] 헤더 항상 위에 고정 시키는 방법 !! (header sticky 주는 방법)

by 포스트it 2024. 2. 23.
728x90
반응형

 

[Html & CSS] 헤더 항상 위에 고정 시키는 방법 !! (header sticky 주는 방법)

헤더에 위치한 메뉴바가 스크롤 내려도 항상 고정 되게 하는 방법입니다 ㅎ

 

예제코드
<!DOCTYPE html>
<html>
<head>
    <title>Sticky Header Example</title>
    <style>
        /* style.css */
.header {
  padding: 20px 0;
  background: #555;
  color: #f1f1f1;
  text-align: center;
}

/* Sticky class is added to the header with JavaScript when it reaches its scroll position */
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 1000;
}

/* Add some top padding to the page content to prevent sudden jumps (due to the header becoming fixed at the top of the page) */
.sticky + .content {
  padding-top: 102px;
}

    </style>
</head>
<body>

<div class="header" id="myHeader">
  <h2>My Sticky Header</h2>
</div>

<div class="content">
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
  <p>Scroll down to see the sticky effect.</p>
  <p>This header will stick to the top of the page when you reach its scroll position.</p>
  <p>Scroll back up to remove the sticky effect.</p>
  <p>More content to show the scroll effect...</p>
</div>

</body>
</html>
<script>
    // script.js
window.onscroll = function() {myFunction()};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
</script>

결과

 

 

728x90
반응형

댓글