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

JavaScript로 열 너비와 열 개수를 한 번에 설정하는 방법

JavaScript에서 columns 속성을 사용하면 단 하나의 선언만으로 요소의 열 너비와 열 개수를 동시에 설정할 수 있습니다. 이 속성은 CSS의 column-width(열 너비)와 column-count(열 개수) 속성을 하나로 묶은 축약형(shorthand)입니다.

columns 속성의 기본 문법

JavaScript에서 columns 속성은 다음과 같은 형태로 설정합니다.

document.getElementById("요소ID").style.columns = "너비 개수";

예를 들어 "70px 2"로 지정하면 각 열의 최소 너비는 70px, 열 개수는 2개로 적용됩니다.

예제

아래 코드는 버튼을 클릭하면 JavaScript로 열 너비와 열 개수를 변경하는 전체 예제입니다.

<!DOCTYPE html>
<html>
   <head>
      <style>
         #myID {
            column-count: 4;
            column-rule: 4px solid yellow;
         }
      </style>
   </head>
   <body>
      <p>Click below to change the column count to 2 and minimum size</p>
      <button onclick="display()">Change Column count and set size</button>
      <div id="myID">
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
         This is demo text. This is demo text. This is demo text. This is demo text.
      </div>
      <script>
         function display() {
            document.getElementById("myID").style.columns = "70px 2";
         }
      </script>
   </body>
</html>

코드 동작 방식

  • 초기 상태에서 #myID 요소에는 column-count: 4가 적용되어 텍스트가 4개의 열로 나뉘어 표시됩니다.
  • column-rule 속성 덕분에 각 열 사이에 노란색 4px 두께의 구분선이 그려집니다.
  • 버튼을 클릭하면 display() 함수가 실행되어 style.columns 값이 "70px 2"로 변경되며, 열 너비와 열 개수가 한 번에 업데이트됩니다.

이처럼 columns 속성을 활용하면 여러 개의 CSS 속성을 개별적으로 수정하지 않고도 다단 레이아웃을 간편하게 제어할 수 있습니다.