궁금한게 많은 코린이의 Developer 노트

[Css] smooth scrolling 본문

css

[Css] smooth scrolling

lemonarr🍋 2023. 12. 2. 06:43

포트폴리오를 만드는 중에, 

어떻게 하면 더 깔끔하게 웹사이트를 보여줄 수 있을까? 하는 생각이 들어

smooth scrolling 이라는 Css를 공부하고 정리해보려 합니다.

 

 

 

크게

부모- <div class="container"></div>

자식- <section class="one"></section>,<section class="two></section>

 

 

HTML

 

 <div class="container">
        <section class="one">
            <h1>First Page</h1>
        </section>
        <section class="two">
            <h1>Second Page</h1>
        </section>
        <section class="three">
            <h1>Third Page</h1>
        </section>
        <section class="four">
            <h1>Fourth Page</h1>
        </section>
</div>

 

 

 

CSS

 
*{
    margin:0;
    padding:0;
    box-sizing: border-box;
    font-family: sans-serif;
}
.container{
    scroll-snap-type: y mandatory;
    overflow-y: scroll;
    height:100vh;
}
section{
    height:100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    color:white;
    scroll-snap-align: start;
}
.one{
background-color:red;
}
.two{
    background-color:green;
}
.three{
    background-color:yellow;
}
.four{
    background-color:blue;
}

 

 

부모의 클래스에

현재 보일 화면의 높이 크기/ scroll-snap-type/overflow-y:scroll; 이것은 반드시 설정해 주어야 한다는 점이다.

height:100vh;
scroll-snap-type: y mandatory;
overflow-y: scroll;

 

 

자식의 클래스에는

현재 보일 화면의 높이 크기/ scroll-snap-align:start를 작성

height:100vh;
scroll-snap-align: start;

 

 

Point는,

부모에는 scroll-snap-type,

자식에는 scroll-snap-align을 적용해주면 된다.

 

 

 

scroll-snap이란 무엇일까?

 

CSS Scroll Snap

 

웹 페이지에서 스크롤 할 때, 요소가 스크롤 되는 위치에 자동으로 스냅 되도록 하는 CSS 속성이다.

스크롤 할 때 중간에 멈추는 경우, 콘텐츠의 일부만 보이게 되는데, 이를 미리 설정한 위치로 자동 스냅하여

자연스러운 스크롤 움직임과 함께 사용자 경험을 더욱 향상시키는 것이다.

 

 

 

 

Scroll Snap type?:

스크롤 스냅이 동작하는 방식,

첫번째 인자로 스냅이 적용될 축을 지정,

두번째 인자로 스냅 적용 방식을 지정한다.

 

.container{
  scroll-snap-type:[scroll snap axis],[scroll snap strictness];
}

 

 

scroll-snap-axis

x: 가로 축으로 snap position 지정

y: 세로 축으로 snap position 지정

 

scroll snap strictness

none: 스냅 X

proximity: 스크롤 위치가 스냅 위치에 가까워지면 자연스럽게 스냅.

mandatory: 스크롤 위치가 스냅 위치와 정확히 일치해야만 스냅. (보통 많이 쓰이는 속성)