HTML,CSS
[CSS] Position:sticky
0에서100
2023. 12. 19. 15:53
728x90
반응형
position: sticky를 활용한 한쪽 고정, 한쪽만 스크롤하게 하기
이 전에는 스크롤하다가 특정 위치에 도달하면 position: fixed를 담은 class를 추가하는 방법으로 사용했는데, position: sticky를 알게된 후에 더욱 쉽게 가능해졌다.
HTML
<div class="sticky-box">
<div class="left">
<p>안녕하세요</p>
<p>저는 스크롤됩니다.</p>
<p>신기하죠?</p>
<p>position: sticky로 쉽게 신기한 걸 구현 가능합니다.</p>
</div>
<div class="right">
<p>나는 고정</p>
</div>
</div>
sticky-box라는 큰 div박스 안에 left와 right로 나눠 left는 스크롤되게, right는 고정되게 html을 구성했다.
CSS
.sticky-box{
margin-top: 500px;
margin-bottom: 500px;
display: flex;
height: 400vh;
}
.left, .right{
width: 50vw;
}
.right{
height: 100vh;
background: #abc;
position: sticky;
top: 0;
}
.right p{
text-align: center;
margin-top: 400px;
font-size: 40px;
}
.left p{
font-size: 30px;
text-align: center;
margin-top: 500px;
}
sticky-box는 충분히 스크롤 될 수 있게 height를 크게 잡고, left와 right는 display: flex로 좌우에 배치되게 했다.
left와 right는 width를 반반 가져갈 수 있게 설정했고, 고정되는 right부분에 position:sticky를 설정했다.
이렇게하니 위와같은 ui를 만들 수 있었다.
- 주의사항
position: sticky를 활용할 때 꼭 top이나 bottom, left, right와 같은 값을 설정해주어야한다.
상황에 따라 중간으로 오게하거나 위에 붙이거나 밑에 붙이면 될거같다.
그리고 보통 overflow-x:hidden으로 초기에 x값이 뷰포트를 넘어갔을 때 스크롤 되지않고 숨겨지게 하는데 이는 position:sticky가 작동할 수 없게 한다. 왜 그런지는 나도 모르겠다.
그럼 어떻게 x축의 스크롤을 없애느냐?
contain:paint를 사용하면 뷰포트 안에서 넘어가는 요소들을 숨겨주고 sticky도 잘 작동한다.
728x90
반응형