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

CSS text-indent 속성으로 텍스트 들여쓰기 쉽게 구현하기

CSS text-indent 속성이란?

CSS의 text-indent 속성은 블록 요소 안에서 텍스트 첫 번째 줄의 들여쓰기(indentation) 크기를 지정하는 속성입니다. 문단 시작 부분에 여백을 만들어 가독성을 높이고 싶을 때 유용하게 활용할 수 있으며, px·em·rem 같은 길이 단위와 퍼센트(%), 그리고 음수 값까지 다양한 방식으로 지정할 수 있습니다.

문법(Syntax)

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

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

양수 값을 지정하면 첫 줄이 오른쪽으로 밀려 들여쓰기 되고, 음수 값을 지정하면 첫 줄이 왼쪽으로 빠져나가는 내어쓰기(hanging indent) 효과를 얻을 수 있습니다. 퍼센트(%) 값은 해당 요소가 포함된 컨테이너의 너비를 기준으로 계산됩니다.

예제 1: 퍼센트(%)와 음수 값 활용하기

다음 예제는 article 요소에는 전체 너비의 25%만큼 들여쓰기를 적용하고, h3 요소에는 -0.8em의 음수 값을 적용해 내어쓰기 효과를 낸 코드입니다.

<!DOCTYPE html>
<html>
<head>
<style>
div {
    display: flex;
    float: left;
    margin: auto;
    padding: 10px;
}
article {
    text-indent: 25%;
    background-color: darkseagreen;
    padding: 15px;
    font-size: 1.3em;
}
h3 {
    text-indent: -0.8em;
}
</style>
</head>
<body>
<div>
<h3>Doing it our way. Nothing gonna turn us back now.</h3>
<article>
This is demo paragraph. This is demo paragraph. This is demo paragraph. 
This is demo paragraph. This is demo paragraph. This is demo paragraph. 
This is demo paragraph. This is demo paragraph. This is demo paragraph. 
This is demo paragraph. This is demo paragraph. This is demo paragraph. </article>
</div>
</body>
</html>

출력 결과

위 코드를 실행하면 다음과 같은 화면을 확인할 수 있습니다.

CSS text-indent 속성으로 텍스트 들여쓰기 쉽게 구현하기

예제 2: 목록(li) 요소에 들여쓰기 적용하기

text-indent 속성은 ul, li처럼 목록을 구성하는 요소에도 적용할 수 있습니다. 아래 예제에서는 각 li 항목의 첫 줄을 23px만큼 들여써서 배경 이미지 위에서 텍스트가 자연스럽게 배치되도록 했습니다.

<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style: none;
    display: flex;
    float: left;
    text-indent: 23px;
    background-image: url("https://www.tutorialspoint.com/angular4/images/angular-4.jpg");
    font-size: 1.5em;
}
li {
    border: thin solid;
}
</style>
</head>
<body>
<ul>
<li>This is demo text. This is demo text.</li>
<li>Angular 4 is a JavaScript framework for building web applications and apps in JavaScript, html, and TypeScript, which is a superset of JavaScript. </li>
<li>Angular provides built-in features for animation, http service, and materials which in turn has features such as auto-complete, navigation, toolbar, menus, etc</li>
<li>This is demo text. This is demo text.</li>
</ul>
</body>
</html>

출력 결과

실행 결과는 다음과 같습니다.

CSS text-indent 속성으로 텍스트 들여쓰기 쉽게 구현하기

마무리 정리

text-indent 속성은 별도의 마진이나 패딩 없이도 텍스트 첫 줄의 들여쓰기를 간단하게 제어할 수 있는 CSS 속성입니다. 퍼센트 값은 부모 컨테이너 너비를 기준으로 반응형 들여쓰기를 구현할 수 있고, 음수 값을 활용하면 내어쓰기 스타일도 손쉽게 만들 수 있다는 점을 기억해 두면 좋습니다.