ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Sass(SCSS) SassScript #1[Data]
    CSS Preproseccor/Sass 2019. 4. 22. 16:51

    SassScript

    Sass는 SassScript라는 작은 확장자 집합을 지원합니다. SassScript를 사용하면 속성에서 변수, 산술 및 추가 함수를 사용할 수 있습니다. 또한 믹스인을 사용할 때 유용합니다.

    Interactive Shell

    Interactive Shell을 사용하여 SassScript를 간단히 테스트할 수 있습니다. 프롬프트 창을 열어 아래와 같이 입력해보세요.

    • Prompt
        $ sass -i
        >> "Hello, Sassy World!"
        "Hello, Sassy World!"
        >> 1px + 1px + 1px
        3px
        >> #777 + #777
        #eeeeee
        >> #777 + #888
        white

    데이터타입 (Data Types)

    SassScript는 다음과 같은 8가지 데이터 유형을 지원합니다.

      * 숫자(numbers) -> 1, 2, 3, 10px 등
      * 문자열(string) -> "foo", 'bar', baz (따옴표 유무와 관계없이)
      * 색상(color) -> blue, #04a3f9, rgba(255,255,255,1)
      * booleand -> true, false
      * nulls -> null
      * 값 리스트 -> 1.5em 1em 0.2em, Helbetica, Arial, sans-serif (공백 또는 쉼표로 구분)
      * 맵핑 -> key1: value1, key2: value2
      * 함수 참조(function references)

    1. 숫자(Numbers)

    Sass의 숫자는 '숫자 자체'와 '단위' 두 가지 구정 요소를 가지고 있습니다. 예를들어 '16px'에서 숫자는 16이고, 단위는 'px'입니다. 숫자는 단위를 가질 수 없으면서 복잡한 단위를 가질 수 있습니다.

      @debug 100; // 100
      @debug 0.8; // 0.8
      @debug 16px; // 16px
      @debug 5px * 2px; // 10px*px (read "square pixels")
      @debug 5.2e3; // 5200
      @debug 6e-2; // 0.06

    단위(Units)

    Sass는 실제 단위 계산 방법을 기반으로 단위 조작에 대한 강력한 지원을 제공합니다. 두 개의 숫자가 곱해지면 그 숫자도 곱해지며, 나눌 때도 마찬가지로 나눠집니다.

      @debug 4px * 6px; // 24px*px (read "square pixels")
      @debug 5px / 2s; // 2.5px/s (read "pixels per second")
      @debug 5px * 30deg / 2s / 24em; // 3.125px*deg/s*em
                                      // (read "pixel-degrees per second-em")
    
      $degrees-per-second: 20deg/1s;
      @debug $degrees-per-second; // 20deg/s
      @debug 1 / $degrees-per-second; // 0.05s/deg

    Sass에서 호환되는 단위를 가지고 있는 숫자를 곱하거나 더할 경우 결과값의 단위는 자동으로 변환됩니다. 호환이 되지 않는 단위를 결합하려고 한다면 오류가 발생합니다.

      // CSS defines one inch as 96 pixels.
      @debug 1in + 6px; // 102px or 1.0625in
    
      @debug 1in + 1s;
      //     ^^^^^^^^
      // Error: Incompatible units s and in.

    Precision

    Sass의 숫자는 소수점 이하 10자리까지 지원합니다.

      * 소수점 뒤의 10자리까지만 CSS 포함
      * == or >= 과 같은 연산을 할 때 소수점 뒤의 10자리까지 동일한 숫자를 갖는다면 두 개의 숫자를 같다고 평가한다.
      * 숫자가 0.0000000001 보다 작을 경우 정수 인수가 필요한 nth() 함수를 위한 정수라고 간주합니다.
    • SCSS
      @debug 0.012345678912345; // 0.0123456789
      @debug 0.01234567891 == 0.01234567899; // true
      @debug 1.00000000009; // 1
      @debug 0.99999999991; // 1

    2. 문자열(Strings)

    문자열은 문자시퀀스(유니코드 코드 포인트) 입니다. Sass는 "Heletica Neue"와 같은 인용된 문자열과 인용되지 않은 문자열을 지원합니다. 또한 CSS에서 나타나는 다양한 종류의 텍스트를 포합합니다.

      /* unquote() 함수를 사용하여 따옴표 붙은 문자열을 따옴표 붙지 않은 문자로 변환할 수 있습니다.
       * quote() 함수는 unquote() 함수와 반대로 동작.
       */
      @debug unquote(".widget:hover"); // .widget:hover
      @debug quote(bold); // "bold"

    Escapes

    CSS의 이스케이프 코드를 지원합니다.

      @debug "\""; // '"'
      @debug \.widget; // \.widget
      @debug "\a"; // "\a" (a string containing only a newline)
      @debug "line1\a line2"; // "line1\a line2"
      @debug "Nat + Liz \1F46D"; // "Nat + Liz 👭"

    인용된 문자열(Quoted)

    인용된 문자열은 "Helvetica Neue"와 같이 큰 따옴표 사이에 있는 문자열을 말합니다. 아래의 사항을 제외한 모든 문자열은 보간법을 사용할 수 있습니다.

      * 이스케이프된 \. \\
      * \' or \"
      * \a (new line)

    인용된 문자열은 Sass 문자열과 동일한 내용을 가진 CSS 문자열로 컴파일됩니다.

      @debug "Helvetica Neue"; // "Helvetica Neue"
      @debug "C:\\Program Files"; // "C:\\Program Files"
      @debug "\"Don't Fear the Reaper\""; // "\"Don't Fear the Reaper\""
      @debug "line1\a line2"; // "line1\a line2"
    
      $roboto-variant: "Mono";
      @debug "Roboto #{$roboto-variant}"; // "Roboto Mono"

    인용되지 않은 문자열(Unquoted)

      @debug bold; // bold
      @debug -webkit-flex; // -webkit-flex
      @debug --123; // --123
    
      $prefix: ms;
      @debug -#{$prefix}-flex; // -ms-flex

    문자열 색인(String Indexes)

    Sass는 문자열의 문자를 참조하는 인덱스라고 하는 번호를 받거나 반환하는 함수를 가지고 있습니다. index 1은 문자열의 첫번째 문자를 나타냅니다. (인덱스가 0부터 시작하는 여러 프로그래밍 언어와 다르다는 점에 주의해주세요.) -1 역시 문자열에서 제일 마지막 문자를 가리킵니다.

      @debug str-index("Helvetica Neue", "Helvetica"); // 1
      @debug str-index("Helvetica Neue", "Neue"); // 11
      @debug str-slice("Roboto Mono", -4); // "Mono"

    3. 색상(colors)

    색상은 16진수 코드(#f2ece4 or #b37399aa), CSS 색상 이름(midnightblue, transparent) 또는 함수 rgb(), rgba(), hsl(), hsla()로 쓸 수 있습니다.

      @debug #f2ece4; // #f2ece4
      @debug #b37399aa; // rgba(179, 115, 153, 67%)
      @debug midnightblue; // #191970
      @debug rgb(204, 102, 153); // #c69
      @debug rgba(107, 113, 127, 0.8); // rgba(107, 113, 127, 0.8)
      @debug hsl(228, 7%, 86%); // #dadbdf
      @debug hsla(20, 20%, 85%, 0.7); // rgb(225, 215, 210, 0.7)

    Sass는 색상을 혼합하거나 기존 색상을 기반으로 채도 및 밝기를 조정하여 새로운 색상을 만드는데 사용할 수 있는 여러 함수들을 지원합니다.

      $venus: #998099;
    
      @debug scale-color($venus, $lightness: +15%); // #a893a8
      @debug mix($venus, midnightblue); // #594d85

    4. 목록(Lists)

    Sass에서의 목록은 다른 언어와 달리 대괄호([])가 필요하지 않습니다. 목록의 요소는 쉼표 또는 공백으로 구분합니다.(Helvetica, Arial, sans-serif), (10px 15px 0 0).

    색인(index)

    목록 역시 Sass의 함수를 사용하여 인덱스라는 숫자를 사용하거나 반환할 수 있습니다. 1부터 시작

    요소에 액세스(Access an Element)

    nth($list, $n) 함수를 사용하여 목록의 지정된 색인에서 요소를 가져올 수 있습니다. 첫번째 인자는 목록 자체이고, 두번째 인자는 츨력하려는 요소의 인덱스입니다.

      @debug nth(10px 12px 16px, 2); // 12px
      @debug nth([line1, line2, line3], -1); // line3

    목록을 사용하는 가장 일반적인 방법 중 하나.

    • Scss

      $sizes: 40px, 50px, 80px;
      
      @each $size in $sizes {
        .icon-#{$size} {
          font-size: $size;
          height: $size;
          width: $size;
        }
      }
    • CSS

      .icon-40px {
        font-size: 40px;
        height: 40px;
        width: 40px;
      }
      
      .icon-50px {
        font-size: 50px;
        height: 50px;
        width: 50px;
      }
      
      .icon-80px {
        font-size: 80px;
        height: 80px;
        width: 80px;
      }

    목록에 추가(Add to a List)

    목록에 요소를 추가할 수 있습니다. append($list, $val) 함수를 사용하면 됩니다. 목록의 끝에 값을 추가한 후 복사본 반환

      @debug append(10px 12px 16px, 25px); // 10px 12px 16px 25px
      @debug append([col1-line1], col1-line2); // [col1-line1, col1-line2]

    목록에서 요소 찾기(Find an Element in a List)

    index($list, $value) 함수 사용

      @debug index(1px solid red, 1px); // 1
      @debug index(1px solid red, solid); // 2
      @debug index(1px solid red, dashed); // null

    찾으려는 값이 목록에 없을 때 index() 함수는 null을 반환합니다. @if or if()를 함께 사용하여 목록에 지정된 값이 포함되어 있는지 여부를 확인할 수 있습니다.

      $valid-sides: top, bottom, left, right;
    
      @mixin attach($side) {
        @if not index($valid-sides, $side) {
          @error "#{$side} is not a valid side. Expected one of #{$sides}.";
        }
    
        // ...
      }

    수정 불가능, 불변성(Immutability)

    Sass의 목록은 수정할 수 없습니다. Sass의 목록 함수들은 원본을 수정하는 대신 새로운 목록을(복사) 반환합니다. 이러한 불변성은 같은 목록이 스타일 시트의 여러 부분에 걸쳐 공유될 때 발생할 수 있는 여러 버그들을 방지합니다. 그러나 동일한 변수에 새 목록을 할당하여 시간이 지남에 따라 상태를 업데이트 할 수는 있습니다.

      $prefixes-by-browser: ("firefox": moz, "safari": webkit, "ie": ms);
    
      @function prefixes-for-browsers($browsers) {
        $prefixes: ();
        @each $browser in $browsers {
          $prefixes: append($prefixes, map-get($prefixes-by-browser, $browser));
        }
        @return $prefixes;
      }
    
      @debug prefixes-for-browsers("firefox" "ie"); // moz ms

    매개변수 목록(Argument Lists)

    임의의 매개변수를 취하는, mixin 또는 functions을 선언할 때 얻는 값은 매개변수 목록으로 알려진 특별한 목록입니다. mixin 또는 function에 전달된 모든 인수를 포함하는 목록과 같은 역할을 합니다. 사용자가 키워드 매개변수를 전달할 경우 매개변수 목록을 keywords() 함수에 전달하여 맵으로 액세스 할 수 있습니다.

    • SCSS

      @mixin syntax-colors($args...) {
      @debug keywords($args); // (string: #080, comment: #800, $variable: $60b)
      
      @each $name, $color in keywords($args) {
          pre span.stx-#{$name} {
            color: $color;
          }
        }
      }
      
      @include syntax-colors(
        $string: #080,
        $comment: #800,
        $variable: #60b,
      )
    • CSS

      pre span.stx-string {
        color: #080;
      }
      
      pre span.stx-comment {
        color: #800;
      }
      
      pre span.stx-variable {
        color: #60b;
      }

    5. Maps

    Maps은 키와 값의 쌍을 가지고 있으며, 특정한 키로 해당 값을 쉽게 찾을 수 있습니다.

      // 목록(lists)와 달리 ()를 꼭 써주어야 한다.
      (<키>:<값>, <키>, <값>)

    빈 list와 빈 maps 모두 ()로 쓰입니다. 모든 maps이 list로 간주됩니다. 다만 (1:4, 2:3)으로 계산될 뿐!

    Mpas 사용

    값 찾기(Look Up a Value)

    maps의 키와 관련된 값을 얻으려면 map-get($map, $key) 함수를 사용하면 됩니다. 매개변수로 주어진 키와 관련된 값을 반환하는데, map에 해당 키가 없으면 null을 반환 합니다.

      $font-weights: ("regular": 400, "medium": 500, "bold": 700);
    
      @debug map-get($font-weights, "medium"); // 500
      @debug map-get($font-weights, "extra-bold"); // null

    Do Something for Every Pair

    아래는 maps을 사용하는 가장 일반적인 방법 중 하나입니다. @each를 사용하였고, maps의 각각의 키/값 쌍에 쉽게 액세스 할 수 있습니다.

    • SCSS

      $icons: ("eye": "\f112", "start": "\f12e", "stop": "\f12f");
      
      @each $name, $glyph in $icons {
        .icon-#{$name}:before {
          display: inline-block;
          font-family: "Icon Font";
          content: $glyph;
        }
      }
    • CSS

      @charset "UTF-8";
      .icon-eye:before {
        display: inline-block;
        font-family: "Icon Font";
        content: "";
      }
      
      .icon-start:before {
        display: inline-block;
        font-family: "Icon Font";
        content: "";
      }
      
      .icon-stop:before {
        display: inline-block;
        font-family: "Icon Font";
        content: "";
      }

    map에 추가(Add to a Map)

    map에 새로운 쌍을 추가하거나 기존 키의 값을 대체하는 것도 할 수 있습니다. map-merge($map1, $map2) 함수는 두 매개변수에 있는 모든 키/값 쌍을 포함하는 새로운 map을 반환합니다.

      $light-weights: ("lightest": 100, "light": 300);
      $heavy-weights: ("medium": 500, "bold": 700);
    
      @debug map-merge($light-weights, $heavy-weights);
      // (
      //   "lightest": 100,
      //   "light": 300,
      //   "medium": 500,
      //   "bold": 700
      // )
    • 인라인 맵과 함께 사용하는 방법

      $font-weights: ("regular": 400, "medium": 500, "bold": 700);
      
      @debug map-merge($font-weights, ("extra-bold": 900));
      // ("regular": 400, "medium": 500, "bold": 700, "extra-bold": 900)
    • 두 맵의 키가 같은 경우 두번째 맵의 값이 반환된 맵에서 사용

      $font-weights: ("regular": 400, "medium": 500, "bold": 700);
      
      @debug map-merge($font-weights, ("medium": 600));
      // ("regular": 400, "medium": 600, "bold": 700)

    수정 불가능, 불변성(Immutability)

    map도 list와 마찬가지로 수정할 수 없습니다.


    6. Boolean(true and false)

    불리언은 논리적인 값을 말합니다. (true and false)

      @debug 1px == 2px; // false
      @debug 1px == 1px; // true
      @debug 10px < 3px; // false
      @debug comparable(100px, 3in); // true

    부울 연산자를 사용하여 부울 연산을 할 수 있습니다. 'and' 연산자를 사용할 경우 좌우 피연산자 모두 true 여야 true를 반환하지만 'or' 연산자는 좌우 피연산자 둘 중 하나만 true여도 true를 반환합니다.

      @debug true and true; // true
      @debug true and false; // false
    
      @debug true or false; // true
      @debug false or false; // false
    
      @debug not true; // false
      @debug not false; // true

    불리언 사용하기(Using Booleans)

    불리언을 사용하여 Sass에서 다양한 작업을 수행할지 여부를 선택할 수 있습니다. @if에서 불리언이 어떻게 사용되는지 아래의 내용을 확인해봅시다.

    • SCSS

      @mixin avatar($size, $circle: false) {
        width: $size;
        height: $size;
      
        @if $circle {
          border-radius: $size / 2;
        }
      }
      
      .square-av { @include avatar(100px, $circle: false); }
      .circle-av { @include avatar(100px, $circle: true); }
    • CSS

      .square-av {
        width: 100px;
        height: 100px;
      }
      
      .circle-av {
        width: 100px;
        height: 100px;
        border-radius: 50px;
      }

    if() 함수의 내부에서 불리언(매개변수)에 따른 반환값.

      @debug if(true, 10px, 30px); // 10px
      @debug if(false, 10px, 30px); // 30px

    7. null

    '값이 없음'을 나타내는 값.

      @debug str-index("Helvetica Neue", "Roboto"); // null
      @debug map-get(("large": 20px), "small"); // null
      @debug &; // null

    목록에 null이 포함되어 있으면, CSS로 컴파일 시 null이 생략된다.

    • SCSS

      $fonts: ("serif": "Helvetica Neue", "monospace": "Consolas");
      
      h3 {
        font: 18px bold map-get($fonts, "sans");
      }
    • CSS

      h3 {
        font: 18px bold;
      }

    속성 값이 null 이면 해당 속성은 완전히 생략된다.

    • SCSS

      $fonts: ("serif": "Helvetica Neue", "monospace": "Consolas");
      
      h3 {
        font: {
          size: 18px;
          weight: bold;
          family: map-get($fonts, "sans");
        }
      }
    • CSS

      h3 {
        font-size: 18px;
        font-weight: bold;
      }

    null 또한 falsey 입니다. null일 수 있는 값을 @if or if()의 조건으로 사용할 수 있습니다.

    • SCSS

      @mixin app-background($color) {
        #{if(&, '&.app-background', '.app-background')} {
          background-color: $color;
          color: rgba(#fff, 0.75);
        }
      }
      
      @include app-background(#036);
      
      .sidebar {
        @include app-background(#c6538c);
      }
    • CSS

      .app-background {
        background-color: #036;
        color: rgba(255, 255, 255, 0.75);
      }
      
      .sidebar.app-background {
        background-color: #c6538c;
        color: rgba(255, 255, 255, 0.75);
      }

    8. 함수(Functions)

    함수도 값이 될 수 있습니다. 함수를 값으로 직접 쓸 수는 없지만 함수의 이름을 [get-function() 함수][]에 전달하여 값으로 얻을 수 있습니다. 함수의 값이 있을 때, 값을 전달할 수 있는 함수를 호출할 수 있습니다.

    • SCSS

      /// Return a copy of $list with all elements for which $condition returns `true`
      /// removed.
      @function remove-where($list, $condition) {
        $new-list: ();
        $separator: list-separator($list);
        @each $element in $list {
          @if not call($condition, $element) {
            $new-list: append($new-list, $element, $separator: $separator);
          }
        }
        @return $new-list;
      }
      
      $fonts: Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
      
      content {
        @function contains-helvetica($string) {
          @return str-index($string, "Helvetica");
        }
        font-family: remove-where($fonts, get-function("contains-helvetica"));
      }
    • CSS

      content {
        font-family: Tahoma, Geneva, Arial, sans-serif;
      }

    'CSS Preproseccor > Sass' 카테고리의 다른 글

    Sass(SCSS) At-Rules #1[@import]  (0) 2019.04.24
    Sass(SCSS) SassScript #2[Operations]  (0) 2019.04.22
    Sass(SCSS) Comments /**/ and //  (0) 2019.04.22
    Sass(SCSS) CSS Extensions  (0) 2019.04.22
    Sass(SCSS) 컴파일  (0) 2019.04.08

    댓글

Designed by Tistory.