position absolute
position
css에서 position은 엘리먼트가 화면에 어떻게 배치되는가를 결정한다.
기본값 : static / relative, absolute, fixed, sticky 으로 변경이 가능하다.
기본값 외 다른 값으로 설정했을 때는 포지셔닝 속성이 있다. top, left, bottom, right 이다.
position : sticky는 스크롤을 해도 자리 고정
absolute position 특징
- 부모 엘리먼트 내부에 속박되지 않고, 독립된 배치 문맥을 가지게 된다.
- 엘리먼트를 브라우저 화면 상에서 어디든지 자유롭게 배치시킬 수 있다.
- 상위 엘리먼트 중 positiin 속성이 relative인 엘리먼트가 있다면, 그 중 가장 가까운 엘리먼트의 내부에서만 엘리먼트를 자유롭게 배치할 수 있다. 즉, 해당 상위 엘리먼트를 기준으로 offset속성이 적용된다.
absolute position 적용
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="prac.css" />
</head>
<body>
<div class="parent">
parent
<div class="child">child 1</div>
<div class="child">child 2</div>
</div>
</body>
</html>
css
.parent {
border: 2px solid blue;
color: blue;
background: lightskyblue;
padding: 1rem;
}
.child {
border: 2px dotted red;
color: red;
background: lightpink;
padding: 1rem;
}
/* Alignment styles */
body {
display: flex;
justify-content: center;
align-items: center;
}
body, html {
height: 100%;
}
* {
box-sizing: border-box;
}
result
position 속성을 바꾸기 전. 부모와 자식 엘리먼트 간 일반적인 배치
html
<div class="parent">
parent
<div class="child">
child 1
</div>
<div class="child abs">
child 2
</div>
</div>
css
.abs {
position: absolute;
}
.parent {
border: 2px solid blue;
color: blue;
background: lightskyblue;
padding: 1rem;
}
.child {
border: 2px dotted red;
color: red;
background: lightpink;
padding: 1rem;
}
result
position 속성을 absolute로 변경하기 위해서 abs 클래스를 추가로 정의했다.
offset 속성을 명시하지 않으면, 기본값인 auto가 적용된다.
따라서 position 속성이 static이었을 때의 위치와 일치하도록 offset 속성값이 자동 지정된다.
(밀려난 child2가 원래 자리에 남아 있는 이유)
css
.abs {
position: absolute;
top: 0;
left: 10px;
}
result
속성값을 지정해주면 child2는 브라우저 상단에 붙고 좌측으로 부터는 10px 떨어진 지점에 배치된다.
htlm
<body>
<div class="parent" style="position: relative;">
parent
<div class="child">child 1</div>
<div class="child abs">child 2</div>
</div>
</body>
result
부모 엘리먼트의 position 속성을 relative로 변경했다.
positioning context가 전체 화면에서 부모 엘리먼트로 변경되어 top, left 속성이 적용된다.
'TIL' 카테고리의 다른 글
2023.04.04_js_일급 객체로서의 함수 (0) | 2023.04.05 |
---|---|
2023.03.23_웹 퍼블리싱 (0) | 2023.03.23 |
2023.03.21_웹 퍼블리싱 (0) | 2023.03.21 |
2023.03.20_웹 퍼블리싱 (0) | 2023.03.20 |
2023.03.16 (0) | 2023.03.16 |