[Online Tutorials] Sticky Navigation Bar On Scroll

✍🏻 고정 네비게이션 바

코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <header>
        <a href="#" class="logo">Logo</a>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Portfolio</a></li>
            <li><a href="#">Team</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </header>
</body>
</html>

@charset "UTF-8";
@import url('http://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800,900&display=swap');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-sefir;
}

body {
    background: #000;
    min-height: 200vh;
}

header {
    z-index: 1;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: 0.6s; /*패딩되는 과정이 transition*/
    padding: 40px 100px;
}

header .logo {
    position: relative;
    font-weight: 700;
    color: #fff;
    text-decoration: none;
    font-size: 2em;
    text-transform: uppercase;
    letter-spacing: 2px;
    transition: 0.6s; /*text-transform이 transition*/
}

header ul {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

header ul li {
    position: relative;
    list-style: none;
}

header ul li a {
    position: relative;
    margin: 0 15px;
    text-decoration: none;
    color: #fff;
    letter-spacing: 2px;
    font-weight: 500px;
    transition: 0.6s;
}

기본적인 header를 만들었다면 JS를 이용해 스크롤 동작에 따라 css를 적용될 수 있도록 하기위해 스크롤 시에 sticky라는 class를 생성해 준다.

<script type="text/javascript">
  window.addEventListener("scroll", function(){
  var header = document.querySelector("header");
  header.classList.toggle("sticky", window.scrollY > 0);
  //Y축 방향으로 스크롤이 발생하면 sticky라는 class를 토글
})
</script>

생성된 .sticky에 스타일을 적용해 준다.

header.sticky {
    padding: 5px 100px;
    background: #fff;
}

header.sticky ul li a, header.sticky .logo {
    color: #000;
}

결과

참고강의

https://www.youtube.com/watch?v=6HFpw5fcaD8&t=42s

좋은 웹페이지 즐겨찾기