CSS 클래스 vs Inline 스타일: 동적 웹 스타일링의 두 얼굴

CSS 클래스로 스타일 관리하기

HTML 파일에 미리 정의된 CSS 클래스는 재사용성이 높고, 스타일의 변경이 필요할 때 CSS 파일만 수정하면 되므로 관리가 편리합니다.

/* styles.css */
.notice {
  padding: 12px 16px;
  margin: 10px 0;
  border: 1px solid #4caf50;
  border-radius: 4px;
  background-color: #d7ffd7;
  font-family: Arial, sans-serif;
  color: #2e7d32;
}

이제 HTML과 자바스크립트를 통해 동적으로 이 클래스를 추가하는 방법을 살펴보겠습니다.

<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>CSS 클래스 사용 예제</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="container"></div>

  <script>
    // 새로운 메시지 박스를 생성합니다.
    const messageBox = document.createElement('div');
    messageBox.innerHTML = "<strong>안내:</strong> 시스템 업데이트가 예정되어 있습니다.";
    
    // CSS 클래스를 한 번에 추가하는 두 가지 방법
    // 방법 1: className을 사용하여 전체 클래스를 지정하기
    // messageBox.className = "notice";

    // 방법 2: classList를 사용해 개별 클래스를 조작하기 (추천)
    messageBox.classList.add("notice");
    
    // container 요소에 메시지 박스를 삽입합니다.
    document.getElementById('container').append(messageBox);
  </script>
</body>
</html>

클래스 조작에는 classList를 사용하는 것이 좋습니다. classList.add(), classList.remove(), classList.toggle() 등을 활용하면 요소의 클래스를 쉽게 관리할 수 있습니다.

인라인 스타일(style 프로퍼티)로 동적 스타일 적용하기

인라인 스타일은 요소의 style 속성을 직접 수정하여 CSS 규칙을 적용하는 방법입니다. 이 방식은 특히 계산된 값(예: 동적으로 계산한 좌표, 크기, 색상 등)을 적용할 때 유용합니다.

<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>동적 스타일 예제</title>
</head>
<body>
  <div id="box" style="width: 150px; height: 150px; background-color: lightblue; text-align: center; line-height: 150px;">
    상자
  </div>

  <script>
    const box = document.getElementById('box');

    // 동적으로 크기와 색상을 변경하는 예제
    function updateBox() {
      // 동적 계산 예: 150px보다 50px 크게
      const newWidth = "200px";
      const newHeight = "200px";
      
      box.style.width = newWidth;
      box.style.height = newHeight;
      box.style.backgroundColor = "salmon";
      box.style.lineHeight = newHeight;
    }

    // 2초 후 업데이트
    setTimeout(updateBox, 2000);
  </script>
</body>
</html>

style 프로퍼티를 수정할 때 CSS 속성 이름은 카멜 케이스(예: background-color → backgroundColor)로 작성해야 합니다. 또한, 숫자 값에는 반드시 단위를 붙여주어야 합니다(예: "20px").

전체 스타일 문자열 다루기: cssText와 setAttribute

때때로 요소의 스타일 전체를 한 번에 설정하거나 변경할 필요가 있습니다. 이때는 cssText 프로퍼티나 setAttribute('style', ...)를 사용할 수 있습니다.

<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>cssText 예제</title>
</head>
<body>
  <div id="card">카드 내용</div>

  <script>
    const card = document.getElementById('card');

    // 기존의 스타일 전체를 새 스타일로 덮어씌우기
    card.style.cssText = `
      background-color: #f5f5f5;
      border: 2px solid #333;
      padding: 20px;
      font-size: 18px;
      text-align: center;
    `;
    
    // 또는 setAttribute를 사용해 동일한 효과를 볼 수 있습니다.
    // card.setAttribute('style', 'background-color: #f5f5f5; border: 2px solid #333; padding: 20px; font-size: 18px; text-align: center;');
  </script>
</body>
</html>

cssText를 사용하면 기존에 요소에 적용되어 있던 모든 인라인 스타일이 삭제되므로, 필요한 경우 기존 스타일을 복사한 후 변경해야 할 수도 있습니다.

계산된 스타일 가져오기: getComputedStyle

elem.style은 오로지 요소의 인라인 스타일만 다룹니다. 실제로 요소에 적용되는 최종 스타일은 CSS 클래스, 상속, 브라우저 기본값 등이 모두 반영된 결과이므로, 이를 읽어오려면 getComputedStyle을 사용해야 합니다.

<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>getComputedStyle 예제</title>
  <style>
    #info {
      font-size: 16px;
      color: darkblue;
      margin: 10px;
    }
  </style>
</head>
<body>
  <div id="info">이 텍스트의 스타일을 확인해보세요.</div>

  <script>
    const infoElem = document.getElementById('info');
    
    // getComputedStyle을 통해 결정된 스타일을 가져옵니다.
    const computed = getComputedStyle(infoElem);
    console.log("폰트 크기:", computed.fontSize);  // 예: "16px"
    console.log("글자 색상:", computed.color);      // 예: "rgb(0, 0, 139)"
    console.log("마진:", computed.margin);           // 예: "10px"
  </script>
</body>
</html>