세로 가운데 정렬하는 방법
CSS에서 텍스트의 가로 가운데 정렬은 text-align 속성을 이용합니다.
text-align : center;
요소의 가로 가운데 정렬은 margin 속성을 이용합니다.
margin-left : auto;
margin-right : auto;
세로로 가운데 정렬하는 여러 방법이 있는데, 그 중 몇 가지를 소개해드립니다.
방법 1 - padding
padding 속성을 바깥쪽 요소에 추가해서 세로 정렬을 가운데로 할 수 있습니다.
<div class="lb-wrap">
<div class="lb-content">
<h1>HELLO</h1>
</div>
</div>
.lb-wrap {
border: 1px solid #444;
background-color: #c4dfb8;
box-shadow: 0px 0px 20px 3px #4285f4;
text-align: center;
color: #fff;
width: 100%;
padding: 125px 0px;
}
.lb-content {
border: 1px solid #444;
background-color: #444;
}
방법 2 - margin
margin 속성을 안쪽 요소에 추가해서 세로 정렬을 가운데로 할 수 있습니다.
<div class="lb-wrap">
<div class="lb-content">
<h1>HELLO</h1>
</div>
</div>
.lb-wrap {
border: 1px solid #444;
background-color: #f9cc9d;
color: #fff;
text-align: center;
width: 100%;
}
.lb-content {
border: 1px solid #444;
background-color: #444;
box-shadow: 0px 0px 15px 5px #4285f4;
margin: 125px 0px;
}
방법 3 - line-height
안쪽 요소의 height와 line-height를 같게 합니다.
<div class="lb-wrap">
<div class="lb-content">
<h1 class="a">HELLO</h1>
</div>
</div>
<div class="lb-wrap">
<div class="lb-content">
<h1 class="b">HELLO</h1>
</div>
</div>
.lb-wrap {
border: 1px solid #444;
text-align: center;
color: #fff;
width: 100%;
margin: 10px 0px;
padding: 100px 0px;
}
.lb-content {
border: 1px solid #444;
background-color: #444;
}
.lb-content h1.a {
height: 100px;
}
.lb-content h1.b {
height: 100px;
line-height: 100px;
}
방법 4 - display: table-cell
바깥쪽 요소에 display: table-cell을 추가하여 표의 셀처럼 만듭니다.
display : table-cell;
그리고 vertical-align: middle을 추가하여 세로 정렬을 가운데로 만듭니다.
vertical-align : middle;
위 방법들과는 다르게, 바깥쪽 요소의 높이(height)를 정해줘야 합니다.
.lb-wrap {
border: 1px solid #444;
text-align: center;
color: #fff;
width: 100vw;
height: 300px;
display: table-cell;
vertical-align: middle;
}
.lb-content {
border: 1px solid #444;
background-color: #444;
}
방법 5 - trasform: translate(-50%, -50%)
trasform: translate(-50%, -50%) 속성을 추가해서 세로 정렬을 가운데로 할 수 있습니다.
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)
방법 6 - flex box
CSS3의 flexible box를 이용하면 쉽게 세로 가운데 정렬을 구현할 수 있습니다.
display: flex;
align-items: center;
justify-content: center;