이번 CSS 튜토리얼에서는 텍스트와 블록 요소를 가운데 정렬하는 방법을 알아봅니다. 레이아웃 작업 시 요소를 수평 또는 수직으로 중앙에 배치해야 하는 경우가 자주 있는데, 이때 활용할 수 있는 다양한 기법을 코드 예제와 함께 하나씩 살펴보겠습니다.
텍스트 요소 가운데 정렬하기
더 큰 요소 안에 포함된 텍스트를 가운데 정렬하려면 text-align: center;를 사용하면 됩니다. 아래 예제처럼 부모 요소에 해당 속성을 지정하면 내부의 문단, 버튼, div 등 모든 인라인 콘텐츠가 중앙으로 정렬됩니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
.div-class {
text-align: center;
background-color: lightblue;
}
button {
width: 200px;
}
</style>
</head>
<body>
<div class="div-class">
<p>I'm a paragraph</p>
<button>I'm a submit button</button>
<div>I'm a div</div>
<p>And all the text is being centered by text-align: center</p>
</div>
</body>
</html>
블록 요소 가운데 정렬하기
블록 요소의 정렬 원리는 HTML 문서의 <body> 태그를 예로 들면 가장 이해하기 쉽습니다. 방법은 간단합니다. 먼저 전체 컨테이너의 너비(width)를 지정한 다음, 마진(margin)을 auto로 설정하면 됩니다. 이렇게 하면 좌우 여백이 균등하게 분배되어 요소가 화면 중앙에 배치됩니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'roboto';
padding: 20px;
}
.div-class {
text-align: center;
background-color: lightblue;
color: black;
}
button {
width: 200px;
}
</style>
</head>
<body>
I'm the top of the body. I control the width of the app container (in this case 800px) and can center the whole app by using <strong>margin: auto</strong>. If you wanted to center <strong>this</strong> text, use text-align: center
<div class="div-class">
<p>I'm a paragraph</p>
<button>I'm a submit button</button>
<div>I'm a div</div>
<p>And all the text is being centered by <strong>text-align: center</strong></p>
</div>
</body>
</html>
이미지 가운데 정렬하기
이미지를 가운데 정렬하려면 CSS 선택자에서 display 속성을 block으로 변경한 뒤, % 또는 px 단위로 이미지의 너비를 지정하고 margin을 auto로 설정합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'Roboto';
padding: 20px;
}
.div-class {
text-align: center;
background-color: lightblue;
color: black;
}
button {
width: 200px;
}
img {
display: block;
margin: 20px auto;
width: 50%;
}
</style>
</head>
<body>
I'm the top of the body. I control the width of the app container (in this case 800px) and can center the whole app by using <strong>margin: auto</strong>. If you wanted to center <strong>this</strong> text, use text-align: center
<div class="div-class">
<p>I'm a paragraph</p>
<button>I'm a submit button</button>
<div>I'm a div</div>
<p>And all the text is being centered by <strong>text-align: center</strong></p>
</div>
<p style="margin: auto; width: 400px;">To center image below, change display to block and then set margins to auto, control the width using px or %</p>
<img src="https://www.placekitten.com/500/301" alt="kittens"/>
</body>
</html>
div 안에서 수직·수평 가운데 정렬하기
<div> 안에서 콘텐츠를 수직으로 가운데 정렬하는 방법은 여러 가지가 있습니다. 상황에 맞게 아래 네 가지 기법 중 하나를 선택해 사용하면 됩니다.
1. padding 활용
가장 간단한 방법은 <div>의 패딩(padding) 값을 조절하는 것입니다. 상하 패딩을 동일하게 부여하면 콘텐츠가 수직으로 중앙에 가까워지며, 여기에 text-align: center를 함께 사용하면 수평 정렬까지 한 번에 처리할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'Roboto';
padding: 20px;
}
.div-class {
text-align: center;
background-color: lightblue;
color: black;
}
button {
width: 200px;
}
img {
display: block;
margin: 20px auto;
width: 50%;
}
</style>
</head>
<body>
I'm the top of the body. I control the width of the app container (in this case 800px) and can center the whole app by using <strong>margin: auto</strong>. If you wanted to center <strong>this</strong> text, use text-align: center
<div class="div-class">
<p>I'm a paragraph</p>
<button>I'm a submit button</button>
<div>I'm a div</div>
<p>And all the text is being centered by <strong>text-align: center</strong></p>
</div>
<p style="margin: auto; width: 400px;">To center image below, change display to block and then set margins to auto, control the width using px or %</p>
<img src="https://www.placekitten.com/500/301" alt="kittens"/>
</body>
</html>
2. line-height 활용
정렬 대상 블록 요소의 높이와 동일한 값으로 line-height를 설정하고 text-align: center와 함께 사용하면 요소를 정확히 중앙에 배치할 수 있습니다. 다만 여러 줄의 텍스트를 정렬해야 한다면 부모와 자식 요소 모두에 line-height를 적용하고, 자식 요소에는 vertical-align: middle과 display: inline-block을 추가해야 합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'roboto';
padding: 20px;
}
#vertical-center-lineheight {
line-height: 200px;
border: 5px double ivory;
text-align: center;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div id="vertical-center-lineheight">
<p>I am vertically centered and horizontally centered in a div using lineheight and text-align: center.</p>
</div>
<div id="vertical-center-lh-multiple">
<p>I am vertically centered and horizontally centered in a div using lineheight, display: inline-block, and vertical-align: middle. Use me when you have multiple lines of text to center across horizontal and vertical axes. </p>
</div>
</body>
</html>
3. transform 활용
position과 transform 속성을 조합하는 방법도 있습니다. 부모 요소에는 position: relative를, 자식 요소에는 절대 위치(absolute)를 지정합니다. 그다음 자식 요소를 top과 left 50% 지점에 배치한 후, transform 속성으로 요소를 자신의 크기만큼 되돌려 이동시켜 정확한 중앙에 맞춥니다. transform 속성에 대해서는 별도 포스트에서 더 자세히 다룰 예정이므로, 지금 완벽하게 이해되지 않아도 걱정하지 않아도 됩니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'roboto';
padding: 20px;
}
#vertical-center-transform {
height: 200px;
position: relative;
border: 5px double ivory;
margin-bottom: 20px;
}
#vertical-center-transform p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="vertical-center-transform">
<p>I am vertically centered and horizontally centered in a div using transform. Text is <strong>NOT</strong> center aligned.</p>
</div>
</body>
</html>
4. flexbox 활용
마지막으로 소개할 방법은 flexbox입니다. 가운데 정렬하려는 자식 요소들을 감싸는 부모 요소에 display: flex를 설정한 뒤, align-items와 justify-content를 center로 지정하면 수직·수평 정렬이 동시에 해결됩니다. 최근에는 가장 널리 사용되는 방식입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<style>
body {
width: 800px;
margin: auto;
background: darkcyan;
color: white;
font-family: 'roboto';
padding: 20px;
}
#vertical-center-flexbox {
height: 200px;
display: flex;
align-items: center;
justify-content: center;
border: 5px double ivory;
}
</style>
</head>
<body>
<div id="vertical-center-flexbox">
<p>I am vertically and horizontally centered in a div using flexbox.</p>
</div>
</body>
</html>
지금까지 소개한 방법들이 레이아웃에서 요소를 가운데 정렬할 때 가장 널리 쓰이는 해결책입니다. 단순 텍스트라면 text-align: center, 블록 요소나 이미지라면 margin: auto, 수직 정렬이 필요하다면 padding, line-height, transform, flexbox 중 상황에 맞는 기법을 선택해 활용해 보세요.