티스토리 뷰

HTML CSS JS

CSS) position: absolute;

Programmers 2021. 8. 30. 08:55
반응형

1) position: absolute;

위치 상 부모 요소를 기준으로 배치
※ position이 지정되어 있는 부모를 기준으로 배치한다. 예제를 봐야 알 수 있다.

 

1. position: absolute;만 2번 div에 적용한 경우

html

<div class="grand-parent">
  <div class="parent">
    <div class="child">1</div>
    <div class="child absolute">2</div>
    <div class="child">3</div>
  </div>
</div>

css

.grand-parent {
  width: 400px;
  height: 300px;
  padding: 30px 100px 100px 30px;
  border: 4px dashed lightgray;
}
.parent {
  width: 400px;
  height: 300px;
  border: 4px dashed gray;
}
.child {
  width: 120px;
  height: 80px;
  background: tomato;
  border: 4px dashed red;
  border-radius: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.absolute {
  position: absolute;
}

출력결과

※ 2번 div뒤에 3번 div가 가려져 있다.

 

2. position: absolute; top: 50px; left:100px;를 2번 div에 적용한 경우

html

<div class="grand-parent">
  <div class="parent">
    <div class="child">1</div>
    <div class="child absolute">2</div>
    <div class="child">3</div>
  </div>
</div>

css

.grand-parent {
  width: 400px;
  height: 300px;
  padding: 30px 100px 100px 30px;
  border: 4px dashed lightgray;
}
.parent {
  width: 400px;
  height: 300px;
  border: 4px dashed gray;
}
.child {
  width: 120px;
  height: 80px;
  background: tomato;
  border: 4px dashed red;
  border-radius: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.absolute {
  position: absolute;
  top: 50px;
  left: 100px;
}

출력결과

※ 2번 div가 grand-parent를 기준으로 되어 있다. 바로 상위요소인 parent에 position이 없기 때문이다.

 

3. position: absolute; top: 50px; left:100px;를 2번 div에 적용한 경우

html

<div class="grand-parent">
  <div class="parent">
    <div class="child">1</div>
    <div class="child absolute">2</div>
    <div class="child">3</div>
  </div>
</div>

css

.grand-parent {
  width: 400px;
  height: 300px;
  padding: 30px 100px 100px 30px;
  border: 4px dashed lightgray;
}
.parent {
  width: 400px;
  height: 300px;
  border: 4px dashed gray;
  position: relative;
}
.child {
  width: 120px;
  height: 80px;
  background: tomato;
  border: 4px dashed red;
  border-radius: 10px;
  font-size: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.absolute {
  position: absolute;
  top: 50px;
  left: 100px;
}

출력결과

※ 2번 div의 바로 상위요소인 parent에 position:relative;를 적용하면 div가 parent를 기준으로 위치가 지정되는 것을 확인할 수 있다.

 

반응형

'HTML CSS JS' 카테고리의 다른 글

CSS) position: sticky;  (0) 2021.08.31
CSS) position:fixed;  (0) 2021.08.31
CSS) position: relative;  (0) 2021.08.30
CSS) position, top, bottom, left, right  (0) 2021.08.30
CSS) clear  (0) 2021.08.30
댓글
공지사항