HTML 문서에서 텍스트를 정렬하려면 CSS 속성을 활용하면 됩니다. 수평 정렬에는 text-align 속성을 사용하고, 수직 정렬에는 padding-top과 padding-bottom, 또는 line-height 속성을 사용합니다.
기본 문법
위에서 언급한 CSS 속성들의 기본 문법은 다음과 같습니다.
Selector {
text-align: center | left | right | justify | inherit | initial;
}
Selector {
padding: /*값*/;
}
Selector {
line-height: /*값*/;
}먼저 텍스트를 수평으로 정렬하는 예제를 살펴보겠습니다.
예제 1: 수평 정렬
<!DOCTYPE html>
<html>
<head>
<title>CSS Text Alignment</title>
<style>
.screen {
padding: 10px;
width: 70%;
margin: 0 auto;
background-color: #f06d06;
text-align: center;
color: white;
border-radius: 0 0 50px 50px;
border: 4px solid #000;
}
.seats span{
margin: 10px;
padding: 10px;
color: white;
border: 4px solid #000;
width: 120px;
display: inline-block;
background-color: #48C9B0;
}
.left{
text-align: left;
}
.right{
text-align: right;
}
.center{
text-align: center;
}
.seats{
text-align: center;
}
</style></head>
<body>
<div class="screen">Screen</div>
<div class="seats">
<span class="left">Adam</span>
<span class="center">Martha</span>
<span class="right">Samantha</span>
</div>
</body>
</html>실행 결과

이번에는 텍스트를 수직으로 정렬하는 예제를 살펴보겠습니다.
예제 2: 수직 정렬
<!DOCTYPE html>
<html>
<head>
<title>CSS Text Alignment</title>
<style>
.screen {
padding: 10px;
width: 70%;
margin: 0 auto;
background-color: #f06d06;
text-align: center;
color: white;
border-radius: 0 0 50px 50px;
border: 4px solid #000;
}
.seats span:not(.withPadding){
margin: 10px;
padding: 10px;
color: white;
border: 4px solid #000;
}
.seats span:not(.vertical){
height: 40px;
display: inline-block;
background-color: #48C9B0;
}
.withPadding{
padding: 20px 20px 0px;
height: 20px;
color: white;
border: 4px solid #000;
}
.vertical{
display: inline-table;
background-color: #48C9B0;
height: 40px;
}
.verticalText {
display: table-cell;
vertical-align: middle;
}
.withLineHeight{
line-height: 40px;
}
.seats{
text-align: center;
}
</style></head>
<body>
<div class="screen">Screen</div>
<div class="seats">
<span class="withPadding">Adam</span>
<span class="withLineHeight">Martha</span>
<span class="vertical"><p class="verticalText">Samantha</p></span>
</body>
</html>실행 결과

수직 정렬 방식 비교
위 예제에서는 세 가지 서로 다른 수직 정렬 기법을 보여줍니다.
- 패딩(padding) 활용: 요소에 상단 패딩 값을 부여해 텍스트를 아래로 밀어내는 방식입니다.
- 라인 높이(line-height) 활용: 줄 높이를 요소 높이와 동일하게 설정하면 텍스트가 자연스럽게 중앙에 위치합니다.
- 테이블 셀(table-cell) 활용:
display: table-cell과vertical-align: middle을 조합하면 높이와 무관하게 항상 세로 중앙 정렬이 가능합니다.
상황에 따라 적합한 방법이 다르므로, 고정된 높이라면 line-height 방식이 간편하고, 유동적인 높이라면 table-cell 방식이 더 안정적입니다.