[HTML/CSS] relative, absolute 사용하기

세상을 바꾸는 개발자·2023년 3월 13일
0

목표



단계 1

4등분

section > div:nth-child(1) {
  top:0;
  left:0;
  background-color:black;
}

section > div:nth-child(2) {
  top:0;
  right:0;
  background-color:gold;
}

section > div:nth-child(3) {
  bottom:0;
  left:0;
  background-color:blue;
}

section > div:nth-child(4) {
  bottom:0;
  right:0;
  background-color:green;
}
  • nth-child()로 div의 몇 번째 자식인지 알려준다.
  • 각각 top, bottom, left, right을 사용하여 위치를 설정한다.


단계 2

4등분한 유령들을 부모에 엘리먼트에 가두기

section {
  width:200px;
  height:200px;
  border:10px solid red;
  margin-top:300px;
  position:relative;
}
  • position:relative를 사용하여 section안에 가둘 수 있다.


단계 3

수평 중앙 정렬

section {
  width:200px;
  height:200px;
  border:10px solid red;
  margin-top:300px;
  margin-left: auto;
  margin-right: auto;
  position:relative;
}
  • margin-left: auto는 왼쪽 여백에 대한 값을 지정하지 않아 오른쪽으로 치우치게 된다.
  • margin-right: auto 또한, 왼쪽으로 치우치게 된다.
  • 따라서 margin-left: auto, margin-right:auto 를 동시에 작성하면 수평 중앙에 정렬하게 된다.


단계 4

중앙 정렬

section {
  width:200px;
  height:200px;
  border:10px solid red;
  position:absolute;
  top:50%;
  left:50%;
}
  • relative 지우고 position:absolute 변경
  • top, left 설정
profile
초심 잃지 않기

0개의 댓글