Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS text-align 속성으로 텍스트 정렬 완벽 가이드

CSS의 text-align 속성을 사용하면 요소 안의 텍스트를 수평 방향으로 정렬할 수 있습니다. 이 속성에는 left(왼쪽 정렬), right(오른쪽 정렬), justify(양쪽 맞춤), center(가운데 정렬) 네 가지 값을 지정할 수 있습니다.

문법(Syntax)

CSS text-align 속성의 기본 문법은 다음과 같습니다.

Selector {
   text-align: /*value*/
}

예제 1

다음 예제는 CSS text-align 속성의 다양한 사용법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: auto;
   padding: 8px;
   max-width: 200px;
   border: thin solid;
}
p {
   text-align: right;
}
div:nth-child(3) {
   text-align: center;
}
div:last-child {
   text-align: justify;
}
</style>
</head>
<body>
<h2>Student Examination Details</h2>
<div>
<div>Student John</div>
<div>
Student Tom
<p>Did not appeared for the exams.</p>
</div>
<div>Student Brad</div>
<div>Did not appeared for only the last exam.</div>
</div>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

CSS text-align 속성으로 텍스트 정렬 완벽 가이드

예제 2

이번에는 테이블 셀(td)에 text-align 속성을 적용하는 예제입니다. :first-of-type 선택자를 활용해 첫 번째 열의 셀만 오른쪽 정렬했습니다.

<!DOCTYPE html>
<html>
<head>
<style>
td {
   padding: 10px;
   box-shadow: inset 0 0 21px yellow;
}
td:first-of-type {
   text-align: right;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<table>
<tr>
<td>This is it!</td>
</tr>
<tr>
<td>Well, this is a demo text!</td>
</tr>
</table>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

CSS text-align 속성으로 텍스트 정렬 완벽 가이드

정리

text-align 속성은 블록 레벨 요소 내부의 인라인 콘텐츠 정렬에 사용되며, 문단, 제목, 테이블 셀 등 다양한 요소에 폭넓게 활용됩니다. 특히 justify 값은 양쪽 여백을 맞춰 신문이나 잡지처럼 깔끔한 레이아웃을 만들 때 유용합니다.