CSS 가로, 세로 가운데 정렬하기

cycorld
Flearning : Solve The Problem
4 min readApr 26, 2016
좋은 구조를 한번 짜두면 두고두고 써먹을 수 있습니다.

CSS를 이용해 컨텐츠를 가로로 가운데 정렬하는 것에 비해 세로로 가운데 정렬하는 것은 쉽지 않습니다. 다양한 브라우저(IE 8이상)에서 잘 작동하는 가운데 정렬 기법을 소개합니다.

블록 만들기

반응형 웹사이트를 만든다면 요소의 width와 height를 주로 percent 단위로 지정합니다. 일반적 css 프레임워크가 그러하듯 여기서 .container 요소를 만들어 보겠습니다.

<div class=”container”>
...
</div>
<style>
...
.container {
width: 80%;
height: 80%;
margin: 40px auto;
background: green;
}
...
</style>

여기서 주의할 점은 .container 요소가 적절히 자리 잡을 수 있도록 스타일을 html, body { width: 100%; height: 100%; } 로 지정합니다.

테이블 형태로 바꾸기

.container 안에서 테이블 패턴을 이용해 수직 중앙정렬을 합니다. .outer로 테이블 태그처럼 동작하는 요소를 만들고 .inner로 테이블 셀처럼 동작하게 만들면 수직 중앙정렬이 가능합니다.

<div class=”container”>
<div class=”outer”>
<div class=”inner”>

</div>
</div>
</div>
<style>
...
.outer {
display: table;
width: 100%;
height: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
text-align: center;
}
...
</style>

끝으로 내용을 담을 .centered 라는 요소를 만듭니다.

<div class=”container”>
<div class=”outer”>
<div class=”inner”>
<div class=”centered”>
...
</div>
</div>
</div>
</div>
<style>
...
.centered {
position: relative;
display: inline-block;

width: 50%;
padding: 1em;
background: orange;
color: white;
}
...
</style>

.centered 속에는 여러분이 원하는 어떤 것이든 배치할 수 있습니다. 높이가 동적으로 변하는 텍스트 블록이나 절대 위치가 지정된 요소 등 마음껏 배치합니다.

<div class=”container”>
<div class=”outer”>
<div class=”inner”>
<div class=”centered”>
<p>Hello, World!</p>
<div class=”badge”>NEW</div>
</div>
</div>
</div>
</div>
<style>
...
.badge {
position: absolute;
width: 60px;
height: 30px;
line-height: 30px;
right: -30px;
top: -15px;
background: red;
}
</style>

정렬 바꾸기

요소의 가로 중앙정렬을 변경하려면 .inner의 text-align 프로퍼티만 수정하면 됩니다. 세로 중앙정렬을 변경하려면 .inner의 vertical-align 프로퍼티를 수정하면 됩니다.

결론

.outer > .inner > .centered 의 마크업(html) 구조만 지킨다면 한번 작성한 css 코드를 다양한 프로젝트에서 쉽게 적용할 수 있습니다. 코딩을 할 때 이렇게 일관성을 유지하기 위한 노력을 기울이면 실력 및 작업 퀄리티 향상에 큰 도움이 됩니다.

전체 코드

참고 : http://webdesign.tutsplus.com/tutorials/the-holy-grail-of-css-centering--cms-22114

--

--