본문 바로가기

웹개발/CSS

[CSS] position : element의 배치

 

position : element 의 배치(4가지 종류)

  1. static : (default) 기본위치(normal) 에 배치
    • top, bottom, left, right 값에 대해 아무런 영향을 받지 않음
  2. relative : 기본위치(normal) 에 대해 '상대적' 배치
  3. fixed : 뷰포트(viewport) 에 대해 '상대적' 배치
  4. absolute : 부모(ancestor) 에 대해 '상대적' 배치
    • 부모가 relative, fixed, absolute 인경우만 작동!
    • 부모가 static 이면, body 에 대해 상대적 배치다.

 => 2,3,4 는 모두 '상대적' 배치 -> top, bottom, left, right 값에 영향 받음

 

 

- 코드

더보기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Position</title>

<style>
div.static {
	border: 3px solid limegreen;
	position: static;
}

div.relative {
	border: 3px solid orangered;
	width: 400px;
	position: relative;
	left:30px;     /* 원래위치부터 왼쪽에서부터 ->(양수라면), left: -30px 도 가능 */
	/* right: 30px;	 left와 right를 동시에 쓸 수는 없음, 오른쪽에서부터 <- */
	/* top: 30px;	위에서부터 */ 
	/* bottom: 30px;	 top과 bottom도 동시에 쓸 수 x */
}

div.fixed {
	border: 3px solid blue;
	width: 300px;
	position: fixed;
	bottom: 0px; /* 뷰포트에 대해 상대적 배치, 뷰포트 아래쪽에서 0px 위로*/
	right: 0px;
}

div.absolute {
	border: 3px solid orchid;
	width: 200px;
	height: 100px;
	position: absolute;
	top:40px;
}
</style>

</head>


<body>
<h2>position: static</h2>
<div class="static">static</div>

<br><hr>

<h2>position: relative</h2>
<div class="relative">relative</div>

<br><hr>

<h2>position: fixed</h2>
<div class="fixed">fixed</div>

<br><hr>

<h2>position: absolute</h2> <!-- 다음 2개 비교 -->
<!--  부모가 relative, fixed, absolute 인 경우 -->
<!-- TODO -->
<div class="relative">부모1-relative
	<div class="absolute">absolute1</div>
</div>

<br>
<!-- 부모가 static 인 경우 -->
<!-- TODO -->
<div class="static">부모2-static
	<div class="absolute">absolute2</div>
</div>

<br><hr>



<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>

- 결과 페이지

 

'웹개발 > CSS' 카테고리의 다른 글

[CSS] float - clear  (0) 2021.09.22
[CSS] float  (0) 2021.09.22
[CSS] 아이콘  (0) 2021.09.22
[CSS] max, min height&width  (0) 2021.09.22
[CSS] Box Model  (0) 2021.09.22