CSS 요소를 수평 및 수직 중앙으로 정렬하는 다양한 방법

웹 개발 과정에서 요소를 부모 컨테이너의 정중앙(수평 및 수직)에 배치해야 하는 상황은 매우 빈번합니다. 정렬 대상은 텍스트일 수도 있고, 이미지나 별도의 블록 요소일 수도 있습니다. 요소의 크기(너비와 높이)가 고정되어 있는지, 혹은 가변적인지에 따라 적절한 구현 방식이 달라집니다.

1. 절대 위치(Absolute Positioning)와 Margin Auto 활용

이 방식은 자식 요소의 크기가 명시적으로 지정되어 있을 때 유효합니다.
<style>
  .container {
    width: 100%;
    height: 400px;
    position: relative;
    border: 2px solid #333;
  }
  .centered-item {
    width: 150px;
    height: 100px;
    background-color: #3498db;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
  }
</style>

<div class="container">
  <div class="centered-item"></div>
</div>
부모에게 relative를 부여하고, 자식 요소의 상하좌우 값을 0으로 설정한 뒤 margin: auto를 주면 브라우저가 남은 공간을 균등하게 배분하여 중앙에 위치시킵니다.

2. 절대 위치와 음수 마진(Negative Margin) 활용

자식 요소의 크기를 정확히 알고 있을 때 사용하는 전통적인 방식입니다.
<style>
  .wrapper {
    position: relative;
    width: 300px;
    height: 300px;
    background-color: #f0f0f0;
  }
  .box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    margin-top: -50px; /* 높이의 절반 */
    margin-left: -50px; /* 너비의 절반 */
    background-color: #e74c3c;
  }
</style>

<div class="wrapper">
  <div class="box"></div>
</div>
요소를 부모의 50% 지점으로 이동시킨 후, 해당 요소의 크기 절반만큼 다시 역방향으로 마진을 주어 중심을 맞춥니다.

3. 절대 위치와 CSS Transform 활용 (크기가 미정인 경우)

요소의 너비나 높이를 미리 알 수 없을 때 가장 유용한 방식 중 하나입니다.
<style>
  .base {
    position: relative;
    width: 100%;
    height: 300px;
    background-color: #ecf0f1;
  }
  .dynamic-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #2ecc71;
    padding: 20px;
  }
</style>

<div class="base">
  <div class="dynamic-content">크기가 가변적인 콘텐츠</div>
</div>
transform: translate(-50%, -50%)는 요소 자신의 현재 크기를 기준으로 계산되므로, 고정 수치를 입력할 필요가 없습니다.

4. Flexbox 레이아웃 활용

현대 웹 표준에서 가장 권장되는 방식입니다. 코드가 간결하며 요소의 크기에 영향을 받지 않습니다.
<style>
  .flex-parent {
    display: flex;
    justify-content: center; /* 수평 중앙 */
    align-items: center;     /* 수직 중앙 */
    width: 100%;
    height: 250px;
    background-color: #9b59b6;
  }
  .flex-child {
    padding: 15px;
    background-color: white;
  }
</style>

<div class="flex-parent">
  <div class="flex-child">Flexbox 중앙 정렬</div>
</div>

5. Grid 레이아웃 활용

가장 짧은 코드로 중앙 정렬을 구현할 수 있는 최신 방식입니다.
<style>
  .grid-parent {
    display: grid;
    place-items: center; /* 수평/수직 동시 정렬 */
    width: 100%;
    height: 250px;
    background-color: #34495e;
  }
  .grid-child {
    background-color: #f1c40f;
    padding: 20px;
  }
</style>

<div class="grid-parent">
  <div class="grid-child">Grid 중앙 정렬</div>
</div>
place-items: center 속성 하나만으로 자식 요소를 완벽하게 정중앙에 배치할 수 있습니다.

6. Table Layout 활용

과거에 많이 쓰였던 방식으로, display: table-cell을 이용합니다.
<style>
  .table-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    width: 400px;
    height: 200px;
    background-color: #bdc3c7;
  }
  .table-content {
    display: inline-block;
    background-color: #d35400;
    width: 80px;
    height: 80px;
  }
</style>

<div class="table-container">
  <div class="table-content"></div>
</div>

요약 및 선택 가이드

요소의 크기를 모르는 경우(Unknown Width/Height)에는 다음 방법들이 효과적입니다:
  • Flexbox: 가장 범용적이고 권장됨
  • Grid: 코드가 매우 간결함
  • Transform: 절대 위치를 사용해야 하는 특수 상황에 유리
단순 텍스트의 경우 line-height를 부모 높이와 맞추거나(단일 행), text-align: center를 활용하는 고전적인 방식도 여전히 유효합니다.

태그: CSS Layout Flexbox CSSGrid Centering

8월 11일 23:33에 게시됨