아이템 가운데 배치하기

clouood·2024년 11월 20일

Question

목록 보기
5/5
post-thumbnail

위 아이템을 수직 중앙 정렬하는 방법은 무엇일까?

수직 중앙 정렬

.container {
  width: 600px;
  height: 400px;
  background-color: gainsboro;
  position: relative;
}

img {
  width: 150px;
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto;
}
	


수직 중앙 정렬 원리

.container => position: relative;
  • container를 기준으로 img의 위치가 계산된다.
img => position: absolute;
  • img는 container를 기준으로 절대적인 위치를 설정한다.
top: 0; bottom: 0;
  • 이미지의 상단과 하단이 컨테이너의 위아래 끝에 맞닿게 설정된다.
margin: auto;
  • 브라우저가 위아래 여백을 자동으로 계산해, 이미지가 컨테이너의 수직 중앙에 위치한다.


그렇다면 위 아이템을 수평 중앙 정렬하는 방법은 무엇일까?

수평 중앙 정렬

.container {
  width: 600px;
  height: 400px;
  background-color: gainsboro;
  position: relative;
}

img {
  width: 150px;
  position: absolute;
  left: 0;
  right: 0;
  margin: auto;
}


수평 중앙 정렬 원리

left: 0; right: 0;
  • 이미지의 왼쪽과 오른쪽이 컨테이너의 양끝에 맞닿게 설정된다.
margin: auto;
  • 브라우저가 좌우 여백을 자동으로 균등하게 계산해, 이미지가 컨테이너의 수평 중심에 위치한다.

수직, 수평 동시 중앙 정렬

img {
  width: 150px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}


완료!

0개의 댓글