Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS만으로 부드러운 스크롤(Smooth Scroll) 효과 구현하는 방법

CSS만으로 부드러운 스크롤(smooth scrolling) 효과를 구현하는 방법을 소개합니다. 핵심은 바로 scroll-behavior 속성입니다.

CSS 부드러운 스크롤이란?

scroll-behavior: smooth; 속성을 html 요소에 적용하면, 앵커 링크(예: #secondSection)를 클릭했을 때 페이지가 순간적으로 점프하지 않고 자연스럽게 스크롤되며 목표 위치로 이동합니다. 별도의 JavaScript 없이 순수 CSS만으로 구현할 수 있어 매우 간편합니다.

예제 코드

<!DOCTYPE html>
<html>
<head>
<style>
    html {
        scroll-behavior: smooth;
    }
    * {
        box-sizing: border-box;
    }
    body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        margin: 0px;
        padding: 0px;
    }
    #firstSection {
        height: 100vh;
        background-color: rgb(119, 77, 219);
        color: white;
        padding: 20px;
    }
    #secondSection {
        height: 100vh;
        color: white;
        background-color: rgb(42, 128, 168);
        padding: 20px;
    }
    a {
        text-decoration: none;
        font-size: 20px;
        font-weight: bold;
        color: yellow;
    }
</style>
</head>
<body>
<h1>Smooth Scroll Example</h1>
<div id="firstSection">
<h2>Section 1</h2>
<p>링크를 클릭하면 "부드러운" 스크롤 효과를 확인할 수 있습니다.</p>
<a href="#secondSection">클릭하여 아래 Section 2로 부드럽게 이동하기</a>
</div>
<div id="secondSection">
<h2>Section 2</h2>
<a href="#firstSection">클릭하여 위 Section 1로 부드럽게 이동하기</a>
</div>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

CSS만으로 부드러운 스크롤(Smooth Scroll) 효과 구현하는 방법

스크롤 링크를 클릭하면 화면이 끊기지 않고 매끄럽게 이동하면서 Section 2로 스크롤됩니다.

CSS만으로 부드러운 스크롤(Smooth Scroll) 효과 구현하는 방법

핵심 포인트 정리

  • scroll-behavior: smooth;html 요소에 적용하면 문서 전체의 스크롤 애니메이션이 활성화됩니다.
  • 앵커 링크 활용href="#secondSection"처럼 대상 요소의 id를 지정하여 이동 위치를 설정합니다.
  • 브라우저 호환성 — Chrome 61+, Firefox 36+, Edge 79+, Safari 15.4+ 등 주요 최신 브라우저에서 지원됩니다.