🌎 Web/CSS

[CSS] 중앙 정렬의 3가지 방법(position, flex, table)

오늘 ONEUL 2022. 4. 3. 23:04

수직정렬, 수평 정렬, 중앙 정렬 중 오늘은 중앙 정렬에 대해 알아보자!

화면 정중앙에 요소를 정렬하는 방법은 크게 3가지가 있다.

  1. position 속성과 transform 속성 사용
  2. flex 속성 사용
  3. table 속성 사용

 


 

 

1. position 속성과 transform 속성 사용

[HTML]

<div class="position-center">
    <div></div>
</div>

[CSS]

.position-center {
    width: 400px;
    height: 300px;
    background-color: green;
    position: relative;
}
.position-center > div {
    width: 100px;
    height: 100px;
    background-color: lightgreen;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

position 속성과 transform 속성을 이용한 중앙 정렬

  1. 부모 <div>position 속성을 relative로 설정한다.
  2. 자식 <div>position 속성을 absolute 로 설정한다.
  3. top: 50%;, left: 50%; 로 설정한다. 이렇게 하면 좌측 상단의 꼭짓점을 기준으로 중앙 정렬이 된다.
  4. transform: translate(-50%, -50%); 로 설정하면 자식 <div> 크기의 수직, 수평 -50% 만큼 이동하여 중앙 정렬된다.

 

 

 

 

2. flex 속성 사용

[HTML]

<div class="flex-center">
    <div></div>
</div>

[CSS]

.flex-center {
    width: 400px;
    height: 300px;
    background-color: blue;
    display: flex;
    justify-content: center;
    align-items: center;
}
.flex-center > div {
    width: 100px;
    height: 100px;
    background-color: lightblue;
}

flex 속성을 이용한 중앙 정렬

  1. 부모 <div>display 속성을 flex 로 설정한다.
  2. 이어서 justify-content: center;, align-items: center; 로 설정한다. (세상 간단)

 

 

 

 

3. table 속성 사용

[HTML]

<div class="table-center">
    <div class="table-inner">
        <div class="table-content"></div>
    </div>
</div>

[CSS]

.table-center {
    width: 400px;
    height: 300px;
    background-color: purple;
    display: table;
}
.table-inner {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.table-content {
    width: 100px;
    height: 100px;
    background-color: darkorchid;
    display: inline-block;

table 속성을 이용한 중앙 정렬

  1. 위의 2가지 방법과는 다르게 HTML 구조를 table-center 안에 table-inner 안에 table-content 로 설정한다.
  2. 가장 상위 <div> 요소인 table-centerdisplay 를 table 로 설정한다.
  3. 중간 <div> 요소인 table-innerdisplay 를 table-cell 로 설정하고, vertical-align: middle;, text-align: center; 로 설정한다.
  4. 가장 안쪽 <div> 요소인 table-contentdisplay 를 inline-block 으로 설정한다.

 

 

 

 

중앙 정렬의 3가지 방법에 대해 알아보았다.

각 상황마다 사용해야 하는 방법이 다르기 때문에 상황에 맞게 사용하면 된다!😉

 

(↓수직 정렬의 방법이 궁금하다면?↓)

2022.03.28 - [CSS] - [CSS] 수직 정렬의 3가지 방법(padding, line-height, position)

 

[CSS] 수직 정렬의 3가지 방법(padding, line-height, position)

수직정렬, 수평 정렬, 중앙 정렬 중 오늘은 수직정렬에 대해 알아보자! 수직정렬에는 3가지 방법이 있다. padding 속성 사용 line-height 속성 사용 position 속성과 transform 속성 사용 전체적으로 사용할

oneul-losnue.tistory.com

 

 

 

 

 

※ 참고자료

https://www.w3schools.com/css/css_align.asp

https://saimplay.tistory.com/115