CSS 중앙 정렬 정리

Web, Development

css에 대해서 물어보는 것 중에서 정렬에 대해서 물어보는 일이 잦아서 여기다가 정리해두려고 한다. 개인적으로는 flex를 이용한 방법이 제일 깔끔하고 flex 하나만 있으면 이것저것 다 할 수 있으니 flex를 쓰는 걸 추천한다.

여기에서 실제 동작을 볼 수 있다.

  • 상황: 자식이 부모에 대한 중앙에 놓고 싶음.
  • 조건 표기: [엘리먼트]:[조건]
    • ex) 자식:width 지정됨

가로

Display에 따라서

display: flex 계열

flex-direction: row 기준으로 설명하지만, column이라면 justify-content를 align-items로 바꾸면 된다.

조건 : 부모:display: flex

부모 {
    justify-content: center;
}

display: block

조건 : 자식:width 지정됨 자식:display: block

자식 {
    margin: 0 auto;
}

display: inline 계열

조건 : 자식:display: inline-block

부모 {
    text-align: center;
}

Position에 따라서

position: absolute or fixed

조건 (absolute): 부모:position이 static 제외한 값으로 설정돼있음 자식: position: absolute
조건 (fixed): 자식: position: fixed 전체 화면 기준으로 정렬

자식 {
    left: 50%;
    transform: translateX(-50%);
}

세로

Display에 따라서

display: flex 계열

flex-direction: row 기준으로 설명하지만, column이라면 align-items를 justify-content로 바꾸면 된다.

조건 : 부모:display: flex

부모 {
    align-items: center;
}

display: table*

조건 계층도:

<부모>
    <자식래퍼>
        <자식>
    </자식래퍼>
</부모>

조건: 부모:display: table 자식래퍼:display: table-cell

자식래퍼 {
    vertical-align: middle;
}

Position에 따라서

position: absolute or fixed

조건 (absolute): 부모:position이 static 제외한 값으로 설정돼있음 자식: position: absolute
조건 (fixed): 자식: position: fixed 전체 화면 기준으로 정렬

/* 중앙 정렬하기 */
자식 {
    top: 50%;
    transform: translateY(-50%);
}

기타

자식 한줄짜리 텍스트

조건: 자식:한줄짜리 텍스트

부모 {
    line-height: (세로 크기)
}