TIL #2 : [CSS] Centering (1/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 1 : 가로 중앙 정렬

1-1. inline 또는 inline-* 같은 element(ex. 텍스트 또는 링크):

  • 부모가 block level이면 text-align:center로 정렬됨

1-2. block level element:

  • margin-left, margin-right에게 auto값을 주면 정렬됨(또는 margin:0 auto을 써서 한번에 줘도 됨) 그러나 너비값이 있어야 함

1-3. block level element이 2개 이상일 경우:
2개 이상의 block level element를 행으로 정렬해야 할 때 디스플레이 타입을 타입을 다르게 하는 경우가 더 효과적일 수 있음

  • 부모: text-align: center
    자식: display: inline-block
  • 부모: display: flex ,justify-content: center

** block level인 element들을 서로 위로 쌓아올릴 때는 auto margin을 사용하면 됨

💎 Case 2 : 세로 중앙 정렬

2-1. inline 또는 inline-* 같은 element(ex. 텍스트 또는 링크):

  1. 하나의 열:
  • 때로는 inline/text element가 그 위와 아래에 동일한 패딩값이 있으면 세로 중앙 정렬로 보일 수 있음
  • 패딩도 옵션이 아니고, wrap가 있는 text가 아닐 경우, line-height을 height와 값을 맞춤
  1. 2개 이상의 열:
  • table cell을 만들어서 vertical-align 속성을 이용
  • flexbox을 사용할 수 있음 그러나 부모 컨테이너가 정해진 높이값(px, %, etc.)이 있어야함.
    하나의 flex-child를 flex-parent안에 정렬해야 하는 경우:
.flex-center-vertically{
display: flex;
justify-content: center;
flex-direction: column;
height: 400px;
}
  • ghost-element technique 사용해서 컨테이너 안에는 height를 최대값으로 설정된 pseudo-element, text는 vertical-align을 적용함
.ghost-center {
  position: relative;
}
.ghost-center::before {
  content: " ";
  display: inline-block;
  height: 100%;
  width: 1%;
  vertical-align: middle;
}
.ghost-center p {
  display: inline-block;
  vertical-align: middle;
}
  1. block level element:
  • element의 height를 아는 경우:
    *** 여기서 margin-top의 값은 padding과 border의 역할을 수행하며 margin-top대신 box-sizing: border-box을 쓸 수 있음
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}
  • element의 height를 모르는 경우:
    높이값 절반을 올린 다음 절반쯤 내리면 됨
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
  • element가 컨테이너의 높이값을 늘여도 되는 경우:
    안에 있는 내용물만 정렬해도 된다면 table이나 display을 사용하여 element들을 테이블로 만들면 됨
    부모: display: table
    자식 display: table-cell; vertical-align: middle;
  • flexbox을 사용할 수 있는 경우:
.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

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

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

0개의 댓글