본문 바로가기

Develop/기타

JavaScript 30 - DAY 03 CSS Variables

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Scoped CSS Variables and JS</title>
</head>
<body>
  <h2>Update CSS Variables with <span class='hl'>JS</span></h2>

  <div class="controls">
    <label for="spacing">Spacing:</label>
    <input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">

    <label for="blur">Blur:</label>
    <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">

    <label for="base">Base Color</label>
    <input id="base" type="color" name="base" value="#ffc600">
  </div>

  <img src="https://source.unsplash.com/7bwQXzbF6KE/800x500">

  <style>
    :root {
      --base: #ffc600;
      --spacing: 10px;
      --blur: 10px;
    }

    img {
      padding: var(--spacing);
      background: var(--base);
      filter: blur(var(--blur));
    }

    .hl {
      color: var(--base);
    }

    /*
      misc styles, nothing to do with CSS variables
    */

    body {
      text-align: center;
      background: #193549;
      color: white;
      font-family: 'helvetica neue', sans-serif;
      font-weight: 100;
      font-size: 50px;
    }

    .controls {
      margin-bottom: 50px;
    }

    input {
      width: 100px;
    }
  </style>

  <script>
    const inputs = document.querySelectorAll('.controls input');

    function handleUpdate() {
      const suffix = this.dataset.sizing || '';
      document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
    }

    inputs.forEach(input => input.addEventListener('change', handleUpdate));
    inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
  </script>


</body>
</html>

목표


CSS 변수를 활용해서 배경색, 여백, 흐림 정도를 설정한다.

코드 분석


:root {
  --base: #ffc600;
  --spacing: 10px;
  --blur: 10px;
}
  • :root는 문서 트리의 최상위 요소를 선택한다. HTML에서는 <html>과 동일하다.
  • —base, —spacing, —blur라는 CSS 변수를 선언한다. 자주 사용되는 설정들을 변수로 선언할 수 있다.
  • :root에서 CSS 변수를 선언한다는 건 전역 변수로 사용하겠다는 것이다.
img {
  padding: var(--spacing);
  background: var(--base);
  filter: blur(var(--blur));
}

.hl {
  color: var(--base);
}
  • var(—변수명)을 통해서 CSS 변수 값을 사용할 수 있다.
const inputs = document.querySelectorAll('.controls input');

function handleUpdate() {
  const suffix = this.dataset.sizing || '';
  document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}

inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
  • controls 클래스 내의 <input> 태그들을 inputs에 담는다.
  • this.dataset.sizing || ''data-sizing 속성에 들어있는 값 또는 빈 문자열을 suffix로 설정한다. (color를 선택하는 <input> 태그는 data-sizing 속성을 따로 가지지 않기 때문에)
  • document.documentElement.style.setProperty(--${this.name}, this.value + suffix)<html>에 style 요소를 부여하고 —이름 : 값+suffix로 내용을 채운다.

추가로 공부한 내용


  • .dataset: data-이름과 같은 사용자 지정 특성을 관리할 수 있다. ex) data-iddataset.id로 접근할 수 있다.