이제 길고 긴 position 속성 값을 알아보는 여정에도 끝이 보이고 있습니다. 고정형 타입인 fixed와 sticky에 대해서 알아보고 position 속성에 대한 내용을 마무리해보도록 하겠습니다.
▷ fixed
우리가 웹 페이지를 볼 때, 우측 하단에 '상담 채팅 연결하기', '이벤트 신청하기' 같은 작은 버튼이 고정된 위치에 출력되는 것을 보신적이 있을 것입니다. 이러한 버튼은 마우스로 페이지를 아무리 스크롤해도 핀으로 꽂아놓은 것처럼 고정되어 있다는 것이 특징입니다.
이 경우가 바로 position의 속성 값을 fixed로 사용했을 때 나타나는 특징입니다. fixed로 position을 설정하게 되면, 이 역시 기본적인 HTML의 요소 배치 컨텍스트에서 벗어나게 되고, 위치 요소(left, right, top, bottom)의 영향을 받게 됩니다. 중요한 것은, 이 위치 요소에 대한 기준점이 어디냐는 것입니다. 자기 자신도, 부모 요소도 아닌 바로 브라우저 그 자체 입니다. 정확히는 뷰포트를 기준으로 하게 됩니다. 그래서 브라우저 크기를 아무리 바꿔도 항상 고정된 위치를 유지하게 되는 것입니다.
우리가 앞서 만들었던 예제의 두 번째 <div> 요소를 fixed로 설정해 살펴보겠습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<title>position</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/css_example.css">
</head>
<body>
<main>
<div>static</div>
<div>fixed</div>
<div>static</div>
</main>
</body>
</html>
main {
position: relative;
width: 500px;
height: 600px;
background: purple;
}
div {
width: 300px;
height: 100px;
border: 1px solid;
background: rgb(22, 177, 61);
text-align: center;
line-height: 100px;
box-sizing: border-box;
}
div:nth-of-type(2) {
position: fixed;
bottom: 8px;
right: 16px;
background: cyan;
opacity: 0.8;
}
▷ sticky
sticky 속성은 fixed와 비슷한 느낌이면서도 스크롤링할 때 효과를 보여주게 됩니다. 예를 들어 어떤 브랜드 홈페이지 같은 곳에서 하단으로 스크롤을 죽 내리는데, 중간에 있던 이미지나 메뉴(내비게이션)가 화면 최상단에 도착하는 순간 턱! 하고 걸린 다음 계속 고정되는 현상을 보신 적 있을 겁니다. sticky를 통해서 이러한 화면 구성을 만들 수 있습니다.
우선, 위의 예제에서 <main> 요소와 두 번째 <div>요소를 수정해 보겠습니다. <main>은 스크롤이 되도록 높이와 overflow를 추가하고, <div>는 sticky 속성 변경과 top 위치 값만 0으로 지정하겠습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<title>position</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/css_example.css">
</head>
<body>
<main>
<div>static</div>
<div>sticky</div>
<div>static</div>
</main>
</body>
</html>
main {
position: relative;
width: 500px;
height: 100px;
overflow: auto;
background: purple;
}
div {
width: 300px;
height: 100px;
border: 1px solid;
background: rgb(22, 177, 61);
text-align: center;
line-height: 100px;
box-sizing: border-box;
}
div:nth-of-type(2) {
position: sticky;
top: 0px;
background: cyan;
opacity: 0.8;
}
'Programming > HTML+CSS' 카테고리의 다른 글
[CSS] 5. 배경 이미지와 그라데이션(2) - background image 1 (0) | 2023.05.03 |
---|---|
[CSS] 5. 배경 이미지와 그라데이션(1) - background color & clip (0) | 2023.05.01 |
[CSS] 4. 레이아웃 설계(3) - position과 위치 속성 3 : absolute (1) | 2023.04.25 |
[CSS] 4. 레이아웃 설계(3) - position과 위치 속성 2 : relative (0) | 2023.04.24 |
[CSS] 4. 레이아웃 설계(3) - position과 위치 속성 1 : static (0) | 2023.04.24 |