SASS 내장 모듈

SASS 내장 모듈

이 글에서는 SASS 내장 모듈을 설명합니다.

기초부터 고급 사용법까지 단계적으로 SASS의 내장 모듈을 다룹니다.

YouTube Video

SASS 내장 모듈

SASS는 다양한 내장 모듈을 제공하며, 이를 사용하면 스타일시트 작성이 더욱 효율적해집니다.

SASS의 내장 모듈이란 무엇인가요?

SASS의 내장 모듈은 재사용 가능한 함수와 믹스인을 제공하는 모듈입니다. 이를 사용하면 복잡한 계산과 커스텀 스타일 작성이 쉬워집니다.

주요 내장 모듈은 다음과 같습니다:.

  • sass:color
  • sass:string
  • sass:math
  • sass:list
  • sass:map
  • sass:selector
  • sass:meta

각 모듈은 특정 작업을 간소화하기 위한 기능을 포함합니다.

각 모듈의 상세 설명과 예제

sass:color 모듈

sass:color 모듈은 색상 조작을 쉽게 해 주는 함수들을 제공합니다.

주요 함수
  • mix(): 두 색을 섞습니다
  • adjust(): 색상, 밝기, 채도 및 기타 속성을 함께 조정합니다
사용 예
 1@use "sass:color";
 2
 3$primary-color: #3498db;
 4$secondary-color: #e74c3c;
 5
 6// Mix two colors with equal weight
 7$blended-color: color.mix($primary-color, $secondary-color, 50%);
 8
 9// Adjust hue by 45 degrees using color.adjust()
10$adjusted-color: color.adjust($primary-color, $hue: 45deg);
11
12div {
13  background-color: $blended-color; // Result of mixing two colors
14  border-color: $adjusted-color;    // Hue adjusted by 45 degrees
15}
  • 이 코드는 두 색을 섞어 새로운 색상을 만들고, 색상(Hue)을 조정한 또 다른 색상도 생성합니다. 생성된 색상은 배경색과 테두리 색으로 요소에 적용됩니다. 이 예시는 색상 조작의 기본을 이해하는 데 도움이 됩니다.

sass:string 모듈

sass:string 모듈은 문자열 조작에 유용한 함수들을 제공합니다.

주요 함수
  • quote(), unquote(): 문자열에 따옴표를 추가/제거합니다
  • length(): 문자열 길이를 가져옵니다
  • to-upper-case(), to-lower-case(): 문자열을 대문자/소문자로 변환합니다
사용 예
 1@use "sass:string";
 2
 3// base values
 4$base-url: "https://example.com";
 5$path: "/assets/style.css";
 6
 7// 1) Combine strings using interpolation and then quote the result
 8$full-quoted: string.quote("#{$base-url}#{$path}");
 9// Example result: "\"https://example.com/assets/style.css\""
10
11// 2) Remove quotes from a quoted string
12$full-unquoted: string.unquote($full-quoted);
13// Example result: https://example.com/assets/style.css
14
15// 3) Get the length of the unquoted string
16$url-length: string.length($full-unquoted);
17// Example output: number of characters in the URL
18
19// 4) Convert strings to upper/lower case and quote for safe CSS output
20$block-name: "main-header";
21// "MAIN-HEADER"
22$upper-quoted: string.quote(string.to-upper-case($block-name));
23// "main-footer"
24$lower-quoted: string.quote(string.to-lower-case("MAIN-FOOTER"));
25
26a::after {
27  /* Use quoted strings for content to ensure valid CSS */
28  content: $full-quoted; /* "https://example.com/assets/style.css" */
29}
30
31:root {
32  /* Insert numeric values with interpolation when needed */
33  --url-length: #{ $url-length }; /* Example: --url-length: 31; */
34}
35
36.header::before {
37  /* Output uppercase version */
38  content: $upper-quoted; /* "MAIN-HEADER" */
39}
40
41.footer::after {
42  /* Output lowercase version */
43  content: $lower-quoted; /* "main-footer" */
44}
  • string.quote()string.unquote()를 사용하면 출력 CSS의 문자열 표현을 정밀하게 제어할 수 있습니다. string.length()는 문자열 길이를 가져오는 함수입니다. string.to-upper-case() / string.to-lower-case()는 클래스 이름 생성이나 BEM 이름 포맷팅에 유용합니다.

sass:math 모듈

sass:math 모듈은 수학적 계산을 위한 함수들을 제공합니다.

주요 함수
  • pow(): 거듭제곱
  • sqrt(): 제곱근
  • abs(): 절댓값
  • round(), ceil(), floor(): 반올림, 올림, 내림
사용 예
 1@use "sass:math";
 2
 3// Using pow() to calculate exponential values
 4$base-size: math.pow(2, 3) * 10px; // 80px
 5
 6// Using sqrt() to compute a square root
 7$root-size: math.sqrt(144) * 1px; // 12px
 8
 9// Using abs() to ensure a positive value
10$offset: math.abs(-15px); // 15px
11
12// Using round(), ceil(), and floor() for different rounding methods
13$rounded: math.round(12.6px); // 13px
14$ceiled: math.ceil(12.1px); // 13px
15$floored: math.floor(12.9px); // 12px
16
17.container {
18  width: $base-size; // 80px
19  height: $root-size; // 12px
20  margin-left: $offset; // 15px
21}
22
23.values {
24  /* Demonstrating different rounding operations */
25  padding: $rounded;  // 13px
26  border-width: $ceiled; // 13px
27  margin-top: $floored; // 12px
28}
  • math.pow()math.sqrt()는 크기 계산에 유용하며, math.abs()와 반올림 관련 함수들은 미세 조정에 도움이 됩니다. 이들을 조합하면 일관된 UI 스케일을 쉽게 계산할 수 있습니다.

sass:list 모듈

sass:list 모듈은 리스트 연산에 특화된 함수들을 제공합니다.

주요 함수
  • append(): 요소를 추가합니다
  • join(): 리스트를 결합합니다
  • nth(): 지정된 위치의 항목을 가져옵니다
  • length(): 리스트 길이를 가져옵니다
사용 예
 1@use "sass:list";
 2
 3// Base list
 4$colors: ("red", "blue", "green");
 5
 6// Add an element to the end of the list
 7$colors-appended: list.append($colors, "yellow");
 8// ("red", "blue", "green", "yellow")
 9
10// Add an element to the beginning of the list using join()
11$colors-prepended: list.join(("black",), $colors);
12// ("black", "red", "blue", "green", "yellow")
13
14// Join two lists together
15$extra-colors: ("pink", "cyan");
16$merged-colors: list.join($colors-prepended, $extra-colors);
17// ("black", "red", "blue", "green", "yellow", "pink", "cyan")
18
19// Get list length
20$total-length: list.length($merged-colors);
21
22// Example usage in a loop: assign each color to a list item
23ul {
24  @for $i from 1 through $total-length {
25    li:nth-child(#{$i}) {
26      /* Get the color at index $i */
27      color: list.nth($merged-colors, $i);
28    }
29  }
30}
  • append()를 사용하여 리스트의 끝에 요소를 추가할 수 있고, join()을 사용해 여러 리스트를 유연하게 결합할 수 있습니다. 리스트의 처음에 요소를 추가하고 싶다면, 단일 요소 리스트를 join()으로 앞에 결합하여 추가할 수 있습니다. length()nth()를 결합하여 동적인 리스트 처리가 필요한 UI 스타일을 더 쉽게 생성할 수 있습니다.

sass:map 모듈

sass:map 모듈은 맵(연관 배열)을 다루는 함수를 제공합니다.

주요 함수
  • get(): 키에 해당하는 값을 가져옵니다
  • set(): 키-값 쌍을 추가하거나 업데이트합니다
  • keys(): 모든 키를 가져옵니다
사용 예
 1@use "sass:map";
 2
 3// Base theme map
 4$theme-colors: (
 5  "primary": #3498db,
 6  "secondary": #e74c3c
 7);
 8
 9// Update or add a value using set()
10$updated-theme: map.set($theme-colors, "warning", #f1c40f);
11// Map now has "warning": #f1c40f added
12
13// Get a value from the map
14$primary-color: map.get($updated-theme, "primary");
15
16// Get all keys from the map
17$all-keys: map.keys($updated-theme);
18// Example: ("primary", "secondary", "warning")
19
20button {
21  /* Apply color retrieved from the theme map */
22  background-color: $primary-color;
23}
24
25.debug {
26  /* Print keys as content for demonstration */
27  content: "#{$all-keys}";
28}
  • map.set()을 사용하면 맵을 동적으로 업데이트할 수 있으며, map.get()과 결합해 유연한 테마 구조를 구성할 수 있습니다. map.keys()를 사용하면 설정 항목을 나열할 수 있어, 확장 가능한 스타일 설계에 도움이 됩니다.

sass:selector 모듈

sass:selector 모듈은 선택자 조작에 유용한 함수들을 제공합니다.

주요 함수
  • nest(): 선택자를 중첩합니다
  • is-superselector(): 선택자 포함 관계를 확인합니다
  • replace(): 선택자를 대체합니다
사용 예
 1@use "sass:selector";
 2
 3// Nest selectors (combine parent and child)
 4$nested-selector: selector.nest(".parent", ".child");
 5// Result: ".parent .child"
 6
 7// Check if one selector is a superselector of another
 8$is-super: selector.is-superselector(".parent", $nested-selector);
 9// true because ".parent" matches all elements that
10// ".parent .child" can match as an ancestor
11
12// Replace part of a selector with another selector
13$replaced-selector: selector.replace(".parent .child", ".child", ".item");
14// Result: ".parent .item"
15
16// Use generated selectors in actual CSS output
17#{$nested-selector} {
18  /* Applies to .parent .child */
19  color: red;
20}
21
22@if $is-super {
23  .info::after {
24    /* Demonstrate boolean result */
25    content: "parent is a superselector";
26  }
27}
28
29#{$replaced-selector} {
30  /* Applies to .parent .item */
31  background: blue;
32}
  • selector.nest()로 선택자를 유연하게 구성하고, selector.is-superselector()로 그 관계를 검증합니다. selector.replace()와 결합하면 고급 선택자 생성 로직을 간결하게 처리할 수 있습니다.

sass:meta 모듈

sass:meta 모듈은 SASS에서 메타프로그래밍에 유용한 기능을 제공합니다.

주요 함수
  • variable-exists(): 변수가 존재하는지 확인합니다
  • global-variable-exists(): 전역 변수가 존재하는지 확인합니다
  • inspect(): 디버깅을 위해 값을 표시합니다
사용 예
 1@use "sass:meta";
 2
 3// Define a global variable
 4$color: #3498db;
 5
 6// Check if a variable exists in the current scope
 7@if meta.variable-exists("color") {
 8  body {
 9    /* Apply style only if $color exists */
10    background-color: $color;
11  }
12}
13
14// Create a local variable inside a block
15.container {
16  $local-size: 20px;
17
18  @if meta.variable-exists("local-size") {
19    /* Demonstrates detection of local variable */
20    width: $local-size;
21  }
22}
23
24// Check if a global variable exists
25$result: meta.global-variable-exists("color"); // true
26
27.debug {
28  /* Use inspect() to output the inspected value as a string */
29  content: meta.inspect($result); // "true"
30}
  • meta.variable-exists()meta.global-variable-exists()를 사용하면 스코프별 변수 상태를 안전하게 판단할 수 있습니다. meta.inspect()는 디버깅에 매우 유용하며 값을 문자열로 표시할 수 있습니다.

실전 예제

여러 내장 모듈을 결합하면 SASS의 표현력이 더욱 향상됩니다. 아래는 color, math, list 모듈을 함께 사용하여 색상 처리와 리스트 작업을 자동화하는 예제입니다.

 1@use "sass:color";
 2@use "sass:math";
 3@use "sass:list";
 4
 5// Base color list
 6$base-colors: (#3498db, #e74c3c, #2ecc71);
 7$darkened-colors: (); // Empty list for processed colors
 8
 9// Loop through each base color and darken it by 10%
10@each $color in $base-colors {
11  $darkened-colors: list.append(
12    $darkened-colors,
13    // Darken color by decreasing lightness by 10%
14    color.adjust($color, $lightness: -10%)
15  );
16}
17
18div {
19  // Apply each processed color to a corresponding <div>
20  @for $i from 1 through list.length($darkened-colors) {
21    &:nth-child(#{$i}) {
22      // Set color by index
23      background-color: list.nth($darkened-colors, $i);
24    }
25  }
26}
  • 이 코드에서는 처리된 색상이 list.append()를 사용하여 순차적으로 추가되며, color.adjust()$lightness: -10%를 사용하여 색상을 10% 어둡게 만듭니다. 마지막으로 @forlist.nth()를 결합해 각 <div>에 서로 다른 배경색을 적용합니다.

요약

SASS의 내장 모듈은 CSS의 유연성을 크게 높여 줍니다. 각 모듈을 이해하고 적절히 활용하면 더욱 효율적이고 유지보수하기 쉬운 스타일시트를 만들 수 있습니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video