CSS : absolute position

2025. 2. 15. 13:29ใ†Style/CSS

๋ฐ˜์‘ํ˜•

position

CSS์—์„œ position ์†์„ฑ์€ ์š”์†Œ๋ฅผ ํ™”๋ฉด์—  ์–ด๋–ป๊ฒŒ ๋ฐฐ์น˜ํ•  ์ง€๋ฅผ ๊ฒฐ์ •ํ•œ๋‹ค.

  • ๊ธฐ๋ณธ๊ฐ’ : static
  • ๋ณ€๊ฒฝ๊ฐ’ : relative, absolute, fixed

position์œผ๋กœ ์†์„ฑ ์š”์†Œ๋ฅผ ์œ„์น˜์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์„ ์ง€์ •ํ•˜๊ณ ,

ํฌ์ง€์…”๋‹ ๊ด€๋ จ ์†์„ฑ์ธ top, left, bottom, right ๋“ฑ์„ ์‚ฌ์šฉํ•˜์—ฌ ์š”์†Œ์˜ offset์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

absolute์˜ ํŠน์ง•

  • ๋ถ€๋ชจ ์š”์†Œ์— ์†๋ฐ•๋˜์ง€ ์•Š์Œ
  • ์š”์†Œ๋ฅผ ํ™”๋ฉด์ƒ ์›ํ•˜๋Š” ์œ„์น˜์— ์ž์œ ๋กญ๊ฒŒ ๋ฐฐ์น˜์‹œํ‚ฌ ์ˆ˜ ์žˆ์Œ
  • ์ƒ์œ„ ์š”์†Œ๊ฐ€ relative๋ผ๋ฉด, ํ•ด๋‹น ์š”์†Œ์˜ ๋‚ด๋ถ€์—์„œ ๋™์ž‘ํ•จ
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="ex.css" type="text/css" />
    </head>
    <body>
        <div class="parent">
            parent
            <div class="child">child 1</div> 
            <div class="child">child 2</div>
            <div class="child_abs">child 3</div>
        </div>
    </body>
</html>
.parent{
    border: 2px solid blue;
    color: blue;
    background-color: lightblue;
    padding:1rem;
}

.child{
    border: 2px solid red;
    color: red;
    background-color: lightcoral;
    padding: 1rem;
}

.child_abs{
    position: absolute;
    border: 2px solid green;
    color: green;
    background-color: lightgreen;
    padding: 2rem;
}

 

absolute ์†์„ฑ์ด ์ ์šฉ๋˜์ง€ ์•Š์€ child ํด๋ž˜์Šค๋ฅผ ๊ฐ€์ง„ child1, 2๋Š” ๋ถ€๋ชจ ์š”์†Œ์— ์ข…์†๋˜์ง€๋งŒ,

absolute ์†์„ฑ์„ ๊ฐ€์ง„ child_abs๋ฅผ ๊ฐ€์ง„ child 3๋Š” ๋ถ€๋ชจ ์š”์†Œ์— ์ข…์†๋˜์ง€ ์•Š์€ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ด ๋•Œ child 3๊ฐ€ ํ™”๋ฉด์— ๋Œ€ํ•ด์„œ๊ฐ€ ์•„๋‹Œ parent์— ๋Œ€ํ•ด ์ •๋ ฌ๋œ ์ด์œ ๋Š”

offset ์†์„ฑ์„ ๋ช…์‹œํ•˜์ง€ ์•Š์œผ๋ฉด ๊ธฐ๋ณธ๊ฐ’์ธ auto๊ฐ€ ์ ์šฉ๋˜๋Š”๋ฐ,

์ด offset auto๊ฐ’์ด position ์†์„ฑ์ด static์ผ ๋•Œ์˜ ์œ„์น˜์™€ ์ผ์น˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

child_abs์˜ top๊ณผ left๋ฅผ 0, 0์œผ๋กœ offset์„ ์ง€์ •ํ•˜๋ฉด ๋ธŒ๋ผ์šฐ์ € ํ™”๋ฉด์— ๋Œ€ํ•ด 0, 0 ์ง€์ ์— ์œ„์น˜ํ•œ๋‹ค.

 

 

๋˜ํ•œ parent์— relative ๊ฐ’์„ ์ง€์ •ํ•˜๋ฉด child_abs์˜ positioning context๊ฐ€ ์ „์ฒดํ™”๋ฉด(viewport)์—์„œ ๋ถ€๋ชจ ์š”์†Œ๋กœ ๋ณ€๊ฒฝ๋˜์–ด

์œ„์น˜๊ฐ€ ์ง€์ •๋จ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

๋ฐ˜์‘ํ˜•