๐Ÿ’ป FE/๐Ÿ“ HTML & CSS

[ HTML / CSS ] z-index, stacking context

Roy Miller 2023. 12. 14. 11:39

 

stacking context

css ํฌ์ง€์…”๋‹ ๋“ฑ์œผ๋กœ ์ธํ•˜์—ฌ ์š”์†Œ๊ฐ€ ๊ฒน์ณ ์กŒ์„ ๊ฒฝ์šฐ ์š”์†Œ์˜ ์Œ“์ž„ ์ˆœ์„œ(stacking context)๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค. 

์ž์ฃผ ์“ฐ์ด๋Š” ์Œ“์ž„ ๋งฅ๋ฝ์˜ ์˜ํ–ฅ์„ ๋ฐ›๋Š” ์š”์†Œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. 

 

  1. ๋ฌธ์„œ์˜ ๋ฃจํŠธ ์š”์†Œ (<html>)
  2. position์ด absolute ๋˜๋Š” relative์ด๊ณ , z-index๊ฐ€ auto๊ฐ€ ์•„๋‹Œ ์š”์†Œ
  3. position์ด fixed ๋˜๋Š” sticky์ธ ์š”์†Œ
  4. flexbox ์ปจํ…Œ์ด๋„ˆ์˜ ์ž์‹ ์ค‘ z-index๊ฐ€ auto๊ฐ€ ์•„๋‹Œ ์š”์†Œ
  5. grid ์ปจํ…Œ์ด๋„ˆ์˜ ์ž์‹ ์ค‘ z-index๊ฐ€ auto๊ฐ€ ์•„๋‹Œ ์š”์†Œ
  6. opacity๊ฐ€ 1๋ณด๋‹ค ์ž‘์€ ์š”์†Œ

z-index ์†์„ฑ์˜ ๊ฐ’

auto

์ƒˆ๋กœ์šด ์Œ“์ž„ ๋งฅ๋ฝ์„ ์ƒ์„ฑํ•˜์ง€ ์•Š๊ณ  ํ˜„์žฌ ์Œ“์ž„ ๋งฅ๋ฝ์—์„œ์˜ ์œ„์น˜๋Š” ๋ถ€๋ชจ ์š”์†Œ์™€ ๋™์ผํ•˜๋‹ค. 

 

์ƒ์ˆ˜

ํ•œ ์ž์‹ ๋งŒ์˜ ์Œ“์ž„ ๋งฅ๋ฝ์„ ์ƒ์„ฑํ•˜๊ณ  ํ•ด๋‹น ๋งฅ๋ฝ์—์„œ ์ž์‹ ์˜ ์œ„์น˜๋ฅผ 0์œผ๋กœ ์„ค์ •ํ•œ๋‹ค. 

๋†’์€ ๊ฐ’์ผ์ˆ˜๋ก ๋‹ค๋ฅธ ์š”์†Œ ์œ„์— ์Œ“์ด๊ฒŒ ๋œ๋‹ค. 

์Œ์ˆ˜๋กœ ์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‚ฎ์ถœ ์ˆ˜ ์žˆ๋‹ค.


์˜ˆ์ œ

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .box {
      width: 100px;
      height: 100px;
      position: absolute;
      border: 2px solid #333;
      text-align: center;
      line-height: 100px;
      font-family: Arial, sans-serif;
    }

    #box1 {
      background-color: #ffcc00;
      left: 50px;
      top: 50px;
      z-index: 1;
    }

    #box2 {
      background-color: #66ccff;
      left: 80px;
      top: 80px;
      z-index: 2;
    }

    #box3 {
      background-color: #99ff99;
      left: 110px;
      top: 110px;
      z-index: 3;
    }
  </style>
</head>
<body>
  <div class="box" id="box1">1</div>
  <div class="box" id="box2">2</div>
  <div class="box" id="box3">3</div>
</body>
</html>

 

 

z-index ๊ฐ’์„ ์‚ด์ง ๋ณ€ํ˜•

      #box1 {
        background-color: #ffcc00;
        left: 50px;
        top: 50px;
        z-index: 2;
      }

      #box2 {
        background-color: #66ccff;
        left: 80px;
        top: 80px;
        z-index: 1;
      }

      #box3 {
        background-color: #99ff99;
        left: 110px;
        top: 110px;
        z-index:3;
      }