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

CSS word-break 속성으로 단어 기준 줄바꿈 구현하기

CSS의 word-break 속성을 사용하면 텍스트가 줄바꿈되는 시점을 단어 단위 또는 문자 단위로 제어할 수 있습니다. 이 속성은 좁은 컨테이너 안에 긴 텍스트를 배치할 때 특히 유용하며, 한글·일본어·중국어처럼 공백 없이 이어지는 CJK 언어의 줄바꿈 처리에도 널리 활용됩니다.

word-break 속성의 주요 값

  • keep-all: 공백이나 하이픈(-)처럼 허용된 지점에서만 줄바꿈합니다. 단어가 통째로 유지되므로 한글 문장에서도 어색하게 중간에 끊기는 현상을 막을 수 있습니다.
  • break-all: 단어의 의미와 상관없이 임의의 문자 위치에서도 줄바꿈을 허용합니다. 영문 텍스트라도 글자 단위로 잘려 나오기 때문에 URL처럼 띄어쓰기 없는 긴 문자열을 처리할 때 유용합니다.

예제 코드

아래 예제에서는 두 개의 문단에 서로 다른 word-break 값을 적용하여 그 차이를 직접 비교해 볼 수 있습니다.

<html>
   <head>
      <style>
         p.text1 {
            width: 140px;
            border: 1px solid #000000;
            word-break: keep-all;
         }
         p.text2 {
            width: 140px;
            border: 1px solid #000000;
            word-break: break-all;
         }
      </style>
   </head>
   <body>
      <b>line break at hyphens:</b>
      <p class = "text1">Tutorials Point originated from the idea that there exists a class of
      readers who respond better to online content and prefer to learn new skills at
      their own pace from the comforts of their drawing rooms.</p>
      <b>line break at any character</b>
     
      <p class = "text2">Tutorials Point originated from the idea that there exists a class of
      readers who respond better to online content and prefer to learn new skills at their
      own pace from the comforts of their drawing rooms.</p>
   </body>
</html>

실행 결과

CSS word-break 속성으로 단어 기준 줄바꿈 구현하기

위 코드를 실행하면 text1(keep-all)은 단어의 경계에서만 줄이 바뀌어 가독성이 자연스럽게 유지되고, text2(break-all)는 컨테이너 폭에 맞춰 어떤 문자에서든 줄이 바뀌는 것을 확인할 수 있습니다. 상황에 맞는 값을 선택하면 반응형 레이아웃에서도 텍스트가 깔끔하게 정렬됩니다.