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

HTML DOM Style textIndent 속성 – 문단 첫 줄 들여쓰기 제어하기

DOM의 textIndent 스타일 속성은 HTML 문서에서 특정 요소 텍스트 첫 번째 줄의 들여쓰기(indentation)를 가져오거나 수정하는 데 사용됩니다. 이 속성을 활용하면 자바스크립트만으로 문단의 시작 위치를 동적으로 조절할 수 있습니다.

구문(Syntax)

textIndent 속성의 기본 사용 구문은 다음과 같습니다.

1. 값 가져오기(Returning textIndent)

object.style.textIndent

2. 값 설정하기(Modifying textIndent)

object.style.textIndent = "value";

속성 값(Values)

value 자리에 들어갈 수 있는 값은 다음과 같습니다.

설명
inherit부모 요소로부터 해당 속성 값을 상속받습니다.
initial해당 속성 값을 브라우저의 기본값으로 되돌립니다.
percentage(%)부모 요소 너비를 기준으로 한 백분율(%) 값으로 들여쓰기를 설정합니다.
lengthpx, em, rem 등 길이 단위를 사용하여 들여쓰기 크기를 지정합니다.

예제(Example)

textIndent 속성의 실제 동작을 확인할 수 있는 예제입니다.

<!DOCTYPE html>
<html>
<head>
<style>
    body {
        color: #000;
        background: lightblue;
        height: 100vh;
    }
    p {
        margin: 1.5rem auto;
    }
    .btn {
        background: #db133a;
        border: none;
        height: 2rem;
        border-radius: 2px;
        width: 40%;
        display: block;
        color: #fff;
        outline: none;
        cursor: pointer;
    }
</style>
</head>
<body>
<h1>DOM Style textIndent Property Example</h1>
<p>
    This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
    This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
    This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
</p>
<button onclick="add()" class="btn">Set textIndent</button>
<script>
    function add() {
        document.querySelector('p').style.textIndent = "80px";
    }
</script>
</body>
</html>

실행 결과(Output)

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

HTML DOM Style textIndent 속성 – 문단 첫 줄 들여쓰기 제어하기

화면의 “Set textIndent” 버튼을 클릭하면, 자바스크립트가 실행되어 문단 텍스트 첫 줄의 들여쓰기가 80px로 변경됩니다.

HTML DOM Style textIndent 속성 – 문단 첫 줄 들여쓰기 제어하기

정리

textIndent 속성은 CSS의 text-indent와 동일한 역할을 하며, DOM에서 직접 접근해 값을 읽거나 쓸 수 있다는 점이 특징입니다. 버튼 클릭 같은 사용자 이벤트에 반응해 문단 들여쓰기를 실시간으로 바꿔야 하는 인터랙티브한 웹 페이지를 만들 때 유용하게 활용할 수 있습니다.