TIL #3 : [CSS] Centering (2/2)

셀레스틴 허·2020년 12월 6일
0
post-thumbnail

Chris Coyier의 Centering in CSS: A Complete Guide을 의역한 글입니다.

I hold no credit or rights to the following article. I merely translated the author's words. If you have more information please visit the site located at the bottom of the page.

💎 Case 3: 가로+ 세로 중앙 정렬

3-1. 너비, 높이 값이 정해진 element:

  • 너비와 높이 값의 절반인 마이너스 margin으로 position: absolute을 설정한 후 50%/50%로 포지셔닝하면 중앙 정렬됨
.parent {
  position: relative;
}

.child {
  width: 300px;
  height: 100px;
  padding: 20px;

  position: absolute;
  top: 50%;
  left: 50%;

  margin: -70px 0 0 -170px;
}

3-2.너비, 높이 값을 모르는 element:

  • transform 속성과 -50% translate을 양방향으로 사용
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

3-3. Flexbox:

  • center 속성 2개를 써야함
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

3-4. Grid:

  • 하나의 element만 정렬해야 하는 경우 권장
body, html {
  height: 100%;
  display: grid;
}
span { /* thing to center */
  margin: auto;
}

💡 혼자 내리는 결론

맙소사 정말 '트릭'에 가까운 코드다.

Credits to:
https://css-tricks.com/centering-css-complete-guide/

profile
Software Developer / 고통은 필연, 괴로움은 선택

0개의 댓글