CSS의 position 속성을 지정하면 페이지를 아래로 스크롤해도 화면 상단에 계속 고정되어 있는 내비게이션 바(탐색 모음)를 손쉽게 구현할 수 있습니다. 이 기능은 사용자가 긴 페이지를 탐색할 때 메뉴에 항상 접근할 수 있도록 도와주기 때문에 실무 웹사이트에서 매우 자주 사용됩니다.
CSS position 속성의 기본 문법
position 속성의 기본적인 작성 형식은 다음과 같습니다.
Selector {
position: /*값*/;
}position 속성에는 static, relative, absolute, fixed, sticky 등의 값을 사용할 수 있으며, 이번 예제에서는 요소를 뷰포트 기준으로 고정하는 fixed 값을 활용합니다.
전체 예제 코드
아래는 자바스크립트와 함께 스크롤 위치를 감지하여 내비게이션 바를 고정하는 완전한 예제입니다.
<!DOCTYPE html>
<html>
<head>
<style>
#navigation-bar {
overflow: hidden;
box-shadow: inset 0 0 20px green;
}
a {
float: left;
display: block;
margin-left: 2%;
padding: 2% 4%;
text-align: center;
color: black;
text-decoration: none;
font-size: 1.2em;
border: 0.5px ridge red;
}
a:hover {
box-shadow: inset 0 0 14px red;
font-size: 1.6em;
}
.content {
background-color: coral;
padding: 16px;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky + .content {
padding-top: 80px;
}
</style>
</head>
<body>
<div class="content"></div>
<div id="navigation-bar">
<a class="active" href="#">logo</a>
<a href="#">SignUp</a>
<a href="#">SignIn</a>
<a href="#">More</a>
</div>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum faucibus ante quis odio rhoncus, sit amet porta nunc venenatis. Vivamus eu ex et risus vehicula semper eu eu elit. Aliquam tempor rutrum neque sit amet aliquam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras non eros ex. Suspendisse placerat tincidunt tortor a semper. Etiam molestie justo ac sapien auctor maximus. Etiam ut ante sollicitudin, tempor mauris nec, malesuada purus. Nunc malesuada sem sed fermentum eleifend. Cras ultrices velit eu blandit lobortis.
</p>
<img src="https://images.unsplash.com/photo-1612305876291-
c369fea489b3?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixlib=rb1.2.1&q=80&w=600" />
</div>
<script>
let nav = document.getElementById("navigation-bar");
let sticky = nav.offsetTop;
window.onscroll = function() {sticker()};
function sticker() {
if (window.pageYOffset >= sticky) {
nav.classList.add("sticky")
} else {
nav.classList.remove("sticky");
}
}
</script>
</body>
</html>동작 원리 살펴보기
1. 스크롤 위치 감지
자바스크립트의 window.onscroll 이벤트는 사용자가 페이지를 스크롤할 때마다 sticker() 함수를 호출합니다. 이 함수 안에서 window.pageYOffset 값(현재 세로 스크롤 위치)이 내비게이션 바의 초기 위치(nav.offsetTop)보다 크거나 같은지 비교합니다.
2. sticky 클래스 토글
스크롤 위치가 임계값을 넘으면 sticky 클래스를 추가하고, 다시 위로 올라가면 클래스를 제거합니다. sticky 클래스에는 position: fixed; top: 0;이 정의되어 있어 내비게이션 바가 화면 최상단에 고정됩니다.
3. 콘텐츠 가림 현상 방지
내비게이션 바가 fixed로 전환되면 문서 흐름에서 벗어나므로 그 아래 콘텐츠가 가려질 수 있습니다. 이를 방지하기 위해 .sticky + .content { padding-top: 80px; } 규칙으로 인접한 콘텐츠 영역에 상단 패딩을 추가했습니다.
실행 결과
위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.


페이지를 아래로 스크롤하면 내비게이션 바가 화면 상단에 고정되어 항상 표시되며, 다시 위로 스크롤하면 원래 위치로 되돌아갑니다.