DISPLAY:TABLE 속성을 이용하여 세로 가운데 정렬 구현하기

2016년 07월 18일
display:center

종종 사이트를 제작할 때 화면의 세로 가운데에 요소를 배치해야 되는 경우가 있는데 가로 가운데 배치는 margin:0 auto; 나 text-align:center을 사용하면 되지만 세로로 가운데 정렬하는 경우에는 보통은 javascript로 top 값을 지정 했었다.

그러나 css의 display:table과 table-cell 속성을 이용하면 좀 더 쉽게 세로 가운데 정렬을 구현할 수 있다.

HTML
<div class="modal-table">
  <div class="modal-cell">
    <div class="box">세로로 가운데 정렬</div>
  </div>
</div>
CSS
.modal-table {
  display: table;
  position: relative;
  width: 100%;
  height: 200px;
  border: 2px solid #666;
}
.modal-cell {
  display: table-cell;
  vertical-align: middle;
}
.box {
  display: block;
  margin: 0 auto;
  padding: 10px;
  width: 90px;
  background-color: #dedede;
  font-size: 12px;
}

가장 상위 요소인 modal-table에 display:table 속성을 추가한 뒤 그 아래 요소인 modal-cell에 display:table-cell; vertical-align:middle; 속성을 추가하면 하위 요소의 세로 정렬이 가능해진다.

마지막으로 하위 요소인 box에 margin:0 auto;를 주면 가로 가운데 정렬을 할 수 있어 가로 세로 전부 가운데 정렬을 구현할 수 있다.