개발 공부/HTML, CSS
HTML/CSS _ 포지션(position) relative,absolute 정리
U_D
2022. 2. 28. 23:34
1. CSS Position이란?
- position 속성을 통해 문서 상에 요소를 배치하는 방법을 지정
- top, right, bottom, left 속성을 통해 요소의 최종 위치를 결정
- 사용법은
- 기준을 잡는다. (예- position: relative;)
- 이동시킨다. (예- top: 50px;)
2. Position 속성
- static : 기본 상태로 포지셔닝이 안된 기준 x 상태
- relative : 요소의 현재 잡은 자리 기준
- fixed : 현재 보고있는 브라우저 기준
- absolute : 가장 가까운 포지셔닝이 된 조상(Ancestor) 요소가 기준
- stickey : 스크롤 영역 기준
3. 요소 위치 속성
Position의 기준에 맞춰 네가지의 방향을 설정할 수 있다.
- top : 요소의 position 기준에 맞는 위쪽 부터의 거리
- bottom : 요소의 position 기준에 맞는 아래쪽 부터의 거리
- left : 요소의 position 기준에 맞는 왼쪽 부터의 거리
- right : 요소의 position 기준에 맞는 오른쪽 부터의 거리
4. 예시
1) relative
: 원래 있던 가운데 자리를 기준으로 위쪽부터 40px 아래로, 좌측부터 40px 우측으로
position: relative;
top: 40px; left: 40px;
2) absolute
: 조상 요소인 env-div에 포지션을 넣어줘서 env-div를 기준으로 우표와 주소가 위치하도록 했다.
↓html
<!DOCTYPE html>
<html>
<head>
<title>우표 붙이기</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="env-div">
<img src="images/envelope.png" width="500">
<img src="images/stamp.png" width="50" class="stamp">
<div class="address">
Sineui Kim<br>
1234 Codeit #101
</div>
</div>
</body>
</html>
↓css
.env-div {
width: 500px;
height: 232px;
position: relative;
}
.address {
font-family: cursive;
position: absolute;
left: 30px;
bottom: 30px;
}
.stamp {
position: absolute;
right: 30px;
top: 30px;
}
↓결과 화면