최원종의 개발 블로그

CSS position 관련 속성(Position, Z-Index) - 12 본문

HTML_CSS/사전학습

CSS position 관련 속성(Position, Z-Index) - 12

chl6698 2026. 4. 17. 16:21

문서 흐름(Document Flow)

HTML 요소는 기본적으로 문서 흐름에 따라 배치됨

 

규칙

- **블록 요소(Block Elements):** 한 줄을 모두 차지하며, 수직으로 쌓임(예: <div>, <p>, <h1>).
- **인라인 요소(Inline Elements):** 한 줄에 나란히 배치되며, 줄 바꿈 없이 옆으로 이어짐(예: <span>, <a>, <strong>).
- **기본 흐름:** 요소는 HTML에 작성된 순서대로 위에서 아래로(블록 요소) 또는 왼쪽에서 오른쪽으로(인라인 요소) 배치됨.

예제코드

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .m-block{
      background-color: #ffccbc;
      padding: 10px;
      margin-bottom: 10px;
      /* div 태그 등 기본 display 속성은 block이다 */
      display: block;
    }
    .m-inline{
      background-color: #c8e7c9;
      border: solid #333;
      padding: 10px;
      /* display: inline; */
      display: inline-block
      ;
    }
    
  </style>
</head>
<body>
  <h2>문서 흐름 이해하기<h2>
     <h3>1. 블럭 요소(수직으로 쌓임)</h3>
  <div class="m-block">블럭요소 1</div>
  <div class="m-block">블럭요소 2</div>
  <div class="m-block">블럭요소 3</div>

  <h3>2. 인라인 요소(수평으로 쌓임)</h3>
  <span class="m-inline"> 인라인 요소 1</span>
  <span class="m-inline"> 인라인 요소 2</span>
  <span class="m-inline"> 인라인 요소 3</span>
</body>
</html>

position (위치 지정)

- **설명:** position 속성은 요소의 위치를 어떻게 배치할지 설정한다. 
HTML 요소는 기본적으로 문서 흐름에 따라 배치되지만, position을 사용하면 이를 변경할 수 있다.

- **값:**
    - static: 기본값, 문서 흐름에 따라 배치(기본 위치).
    - relative: 문서 흐름에 따라 배치되지만, top, left, right, bottom으로 원래 위치에서 상대적으로 이동.
    - absolute: 문서 흐름에서 벗어나며, 가장 가까운 position이 relative/absolute/fixed인
    부모 요소를 기준으로 top, left, right, bottom으로 이동.
    - fixed: 문서 흐름에서 벗어나며, 뷰포트(화면)를 기준으로 top, left, right, bottom으로 이동(스크롤해도 고정됨)
    
- **주의사항:** relative, absolute, fixed를 사용할 때는
top, left, right, bottom 속성을 함께 설정해야 위치를 조정할 수 있다.

 


실습 코드

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        background-color: black;
      }
      .star {
        position: absolute;
        font-size: 30px;
      }
      .spaceship {
        font-size: 30px;
        /* 부모 태그 기주으로 결정 됨 */
        /* position: absolute; */
        /* 화면 기준으로 고정 fixed */
        position: fixed;
        top: 50px;
        right: 50px;
        z-index: 100;
      }
    </style>
  </head>
  <body>
    <div class="star" style="top: 50px; left: 100px">⭐​</div>
    <div class="star" style="top: 150px; left: 300px">⭐​</div>
    <div class="star" style="top: 350px; left: 150px">⭐​</div>
    <div class="star" style="top: 2200px; left: 450px">⭐​</div>
    <div class="planet"></div>
    <div class="spaceship">🚀​</div>
  </body>
</html>