Post

position 속성

CSS Position 속성

소개

CSS의 position 속성은 요소를 문서 내에서 어떻게 배치할지를 결정합니다. 이 속성은 다섯 가지 주요 값(static, relative, absolute, fixed, sticky)을 가지며, 각 값은 요소의 배치 방식을 다르게 정의합니다.

Position 값

static

position: static은 기본값으로, 요소는 일반적인 문서 흐름에 따라 배치됩니다. top, right, bottom, left 속성은 무시됩니다.

1
2
3
.element {
  position: static;
}

relative

position: relative는 요소를 일반적인 문서 흐름에 따라 배치한 후, top, right, bottom, left 속성을 사용하여 이동시킵니다. 이동된 공간은 원래 위치를 유지합니다.

1
2
3
4
5
.element {
  position: relative;
  top: 10px;
  left: 20px;
}

absolute

position: absolute는 요소를 일반적인 문서 흐름에서 제거하고, 가장 가까운 positionrelative, absolute, fixed인 조상 요소를 기준으로 배치합니다. 조상 요소가 없으면 body를 기준으로 합니다.

1
2
3
4
5
6
7
8
9
.container {
  position: relative;
}

.element {
  position: absolute;
  top: 10px;
  right: 20px;
}

fixed

position: fixed는 요소를 일반적인 문서 흐름에서 제거하고, 뷰포트(viewport)를 기준으로 배치합니다. 스크롤해도 요소는 같은 위치에 고정되어 있습니다.

1
2
3
4
5
.element {
  position: fixed;
  top: 0;
  right: 0;
}

sticky

position: sticky는 요소를 일반적인 문서 흐름에 따라 배치하다가 스크롤 위치가 임계점에 도달하면 뷰포트에 고정됩니다. 부모의 overflow 속성이 hidden, scroll, auto가 아니어야 합니다.

1
2
3
4
.element {
  position: sticky;
  top: 0;
}

예제

기본 사용법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .static {
      position: static;
    }
    .relative {
      position: relative;
      top: 10px;
      left: 10px;
    }
    .absolute {
      position: absolute;
      top: 10px;
      left: 10px;
    }
    .fixed {
      position: fixed;
      top: 0;
      left: 0;
    }
    .sticky {
      position: sticky;
      top: 0;
    }
  </style>
  <title>Position 예제</title>
</head>
<body>
  <div class="static">Static</div>
  <div class="relative">Relative</div>
  <div class="absolute">Absolute</div>
  <div class="fixed">Fixed</div>
  <div class="sticky">Sticky</div>
</body>
</html>

결론

CSS의 position 속성은 요소의 배치 방법을 정의하는 중요한 속성입니다. static, relative, absolute, fixed, sticky 값을 통해 다양한 배치 방법을 구현할 수 있습니다. 각 값을 이해하고 적절히 사용하는 것이 웹 페이지의 레이아웃을 효과적으로 설계하는 데 중요합니다.

다음시간에 계속…

image

This post is licensed under CC BY 4.0 by the author.