요소의 가운데 정렬
요소의 가운데 정렬
margin : auto
div 태그는 block 레벨이기 때문에 콘텐츠 영역 외에 나머지 부분이 모두 마진으로 들어간다.
그렇기에 text-align : center로는 컨텐츠를 가운데 정렬할 수 없다.
그렇다면 이러한 경우에는 어떻게 해야할까?
이 경우에는 오른쪽으로 치우쳐져 있는 margin 값을 통해 가운데 정렬을 할 수 있다.
margin : auto를 사용하면 먹히지 않던 정렬이 된다.
CSS
.box {
width: 200px;
height: 100px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: blue;
}
HTML
<h3>margin: auto</h3>
<div class="box">
<div class="inner"></div>
</div>
text-align:center
그러나 button이나 span과 같은 인라인 요소들은 margin을 조정하는 것이 아니라
text-align:center를 사용하여 가운데 정렬을 할 수 있다.
CSS
.box {
width: 200px;
height: 100px;
background-color: red;
text-align:center;
}
HTML
<h3>text-align: center</h3>
<div class="box">
<button>
click
</button>
</div>
translate
transform의 translate를 사용하여 가운데 정렬을 할 수 있다.
translate는 자기 자신 기준으로 움직이므로 홈페이지 전체에서 가운데 정렬을 하는 경우에는 사용하지 않는다.
홈페이지 가운데 정렬을 하는 경우는 아래에서 따로 다룰 것이다.
CSS
.box {
width: 200px;
height: 100px;
background-color: red;
text-align:center;
}
.inner {
width: 100px;
height: 50px;
background-color: blue;
transform: translate(50%, 50%);
}
HTML
<h3>translate</h3>
<div class="box">
<div class = 'inner'>
</div>
</div>
세로 정렬
text-align:center를 사용하는 것은 가로로는 정렬이 되지만 세로로는 정렬이 되지 않는다.
그렇기에 사람들은 약간의 꼼수같은 방법으로 정렬을 한다. 그렇기에 이 방법은 한줄 이상인 경우에는 사용할 수 없기에 한 줄을 넘어가지 않는 경우에 사용 가능하다.
line-height를 사용하여 정렬하는 것이다.
line-height을 부모상자만큼 만들게 되면 한줄의 높이가 그만큼 되므로 자동적으로 가운데로 오게 된다.
CSS
.box {
width: 200px;
height: 100px;
background-color: red;
}
.box1 h1 {
text-align: center;
line-height: 100px;
}
HTML
<h3>line-height</h3>
<div class="box box1">
<h1>
hello
</h1>
</div>
위의 예시들 처럼 부모 요소 안에서 가운데 정렬과 다르게 보여지는 화면 전체에서 중앙 정렬은 조금 다르다.
CSS
.box {
position: absolute;
top : 50%;
left: 50%;
background-color: red;
transform: translate(-50%, -50%);
}
HTML
<div class="box box1">
<h1>
hello
</h1>
</div>
먼저 position을 absolute를 하고 top과 left로 전체 화면 중앙으로 이동한다.
그런데 거기서 제대로 된 가운데 정렬이 되지 않는다. 왜냐하면 해당 박스의 왼쪽 윗 부분이 페이지의 정중앙에 위치하므로 약간 오른쪽 아래로 치우쳐져 있다.
그렇기에 translate(-50%, -50%)를 사용하여 자신을 기준으로 이동시켜서 정확한 가운데 정렬을 시켜준다.
이 부분이 이해가 가지 않으신다면 translate를 제거한 것과 제거하지 않은 것을 놓고 비교하면 그 차이를 알 수 있다.