SASS | Цветовые функции

Опубликовано: 2 Марта, 2022

Компоненты цвета: прежде чем мы перейдем к функциям цвета SASS, давайте удостоверимся, что мы знаем элементы цвета, которые они изменяют. Простая теория цвета делит любой цвет на три основных компонента: оттенок, насыщенность и значение.

  • ОТТЕНОК (также называемый «местный цвет») - это обычно цвет, о котором мы говорим. Нравится: Голубое небо, Желтое солнце.
  • Насыщенность - это мера, которая показывает количество оттенков, существующих в цвете, то есть интенсивность цвета. Например, цвет облаков меняется с белого на синий и затем на черный.
  • Значение является мерой светлоты или темноты цвета. Например, обычная коричневая земля, часть которой освещена солнечным светом, а другая часть находится в тени.

Цветовые модели: в технологическом мире цвета представлены как RGB или HSL. (Существуют различные другие модели, такие как CMYK и LAB, но только RGB и HSL относятся к разработке SASS.)

Значения RGB являются мерой количества «красного», «зеленого» и «синего» в основном цвете. Каждый компонент имеет значение от 0 (цвет отсутствует) до 255 (полный цвет). Цвета RGB в основном выражаются в шестнадцатеричном формате, например # 0000ff или # 2abd35.

HSL означает «оттенок, насыщенность и яркость». Можно также получить модели HSV (здесь V означает «значение») или HSB (здесь B означает «яркость»). Например, Photoshop использует HSB.

hsl ($ hue, $ saturation, $ value): оттенок указывается в градусах на круге цветов (чистый красный - 0, чистый зеленый - 120 и чистый синий - 240), тогда как насыщенность и значение указываются в процентах .

Это довольно простой пример. При переключении между RGB и HSL компонент оттенка цвета иногда может стать довольно некрасивым. Например, оттенок # ac4138 составляет 4,65517 градусов.

непрозрачность: в цветовых моделях RGB и HSL непрозрачность задается через альфа-значение от 0 до 100%, где 0 означает полную прозрачность, а 100% - полную непрозрачность.

Цветовые функции SASS: rgb () и hsl () используются для создания более краткого CSS. Все современные браузеры поддерживают функции CSS rgba () и hsla (), поэтому транспилятор SASS сохранит те же функции в CSS.

The rest three functions, “grayscale(), invert() and complement()” make a new color based on the current one. Invert() function, inverts each red, green and blue value and complement(), rotates the color 180 degrees, gives quite similar but not identical results.

  1. rgb($red, $green, $blue): This method creates an opaque color based on the given decimal values or percentages.
    • Example:
      rgb(252, 186, 3)
    • Output:
      #fcba03
      rgb(50%, 50%, 100%)
    • Output:
      #8080ff
  2. rgba($red, $green, $blue, $alpha): This method creates a color based on the given decimal or percentage values at the given opacity.
    • Example:
      rgba(71, 214, 75, 0.5 )
    • Output:
      rgba(71, 214, 75, 0.5 )
  3. hsl($hue, $saturation, $lightness): This method creates an opaque color based on the given hue (in degrees), saturation and lightness (in percentages).
    • Example:
      hsl(122, 64, 56)
    • Output:
      #47d74c
  4. hsla($hue, $saturation, $lightness, $alpha): This method create a color based on the specified hue, saturation and lightness at the specified opacity.
    • Example:
      hsla(122, 64, 56, 50)
    • Output:
       hsla(122, 64, 56, 50)
  5. grayscale($color): This method returns a gray value that has the same intensity as “color”.
    • Example:
      grayscale(#ad4038)
    • Output:
      #737373
  6. complement($color): This method returns a color that has the same saturation and value, but has a hue 180 degrees different from the hue of “color”.
    • Example:
      complement(#47d74c)
    • Output:
      #d747d2
  7. invert($color): This method returns the inverse of the individual red, green and blue components of “color”.
    • Example:
      invert(#ad4038)
    • Output:
      #52bfc7

SASS Component Extraction Functions:

  1. red($color): This method returns the red component of “color”.
    • Example:
      red(#d747d2)
    • Output:
      215
  2. green($color): This method returns the green component of “color”.
    • Example:
      green(#d747d2)
    • Output:
      71
  3. blue($color): This method returns the blue component of “color”.
    • Example:
      blue(#d747d2)
    • Output:
      210
  4. hue($color): This method returns the hue component of “color”.
    • Example:
      hue(#d747d2)
    • Output:
       302°
  5. saturation($color): This method returns the saturation component of “color”.
    • Example:
      saturation(#d747d2)
    • Output:
      64%
  6. lightness($color): This method returns the lightness component of “color”.
    • Example:
      lightness(#d747d2)
    • Output:
      56%
  7. alpha($color): This method returns the alpha channel of color as a number between 0 and 1.
    • Example:
      alpha(#d747d2)
    • Output:
      1
  8. opacity($color): This method returns the opacity of color as a number between 0 and 1.
    • Example:
      opacity(rgba(215, 71, 210, 0.7);
    • Output:
      0.7

SASS Manipulate Color Functions

  1. mix($color1, $color2, $weight): This method creates a color that is the combination of color1 and color2. The weight parameter must be between 0% and 100%. A larger weight means that more of color1 should be used. A smaller weight means that more of color2 should be used. The default value is 50%.
  2. adjust-hue($color, $degrees): This method adjusts the color’s hue with a degree from -360deg to 360deg.
    • Example:
      adjust-hue(#7fffd4, 80deg);
    • Output:
      #8080ff
  3. adjust-color($color, $red, $green, $blue, $hue, $saturation, $lightness, $alpha): This method adjusts one or more parameters by the given amount. This function adds or subtracts the given amount to/from the existing color value.
  4. change-color($color, $red, $green, $blue, $hue, $saturation, $lightness, $alpha): This method sets one or more parameters of a color to new values.
    • Example:
      change-color(#7fffd4, red: 255);
    • Output:
       #ffffd4
  5. scale-color($color, $red, $green, $blue, $saturation, $lightness, $alpha): This method scales one or more parameters of color.
  6. rgba($color, $alpha): This method creates a new color with the given alpha channel.
    • Example:
      rgba(#7fffd4, 30%)
    • Output:
      rgba(127, 255, 212, 0.3)
  7. lighten($color, $amount): This method creates a lighter color with the amount between 0% and 100%. The amount parameter increases the HSL lightness by that percent.
  8. darken($color, $amount): This method creates a darker color with the amount between 0% and 100%. The amount parameter decreases the HSL lightness by that percent.
  9. saturate($color, $amount): This method creates a more saturated color with the amount between 0% and 100%. The amount parameter increases the HSL saturation by that percent.
  10. desaturate($color, $amount): This method creates a less saturated color with the amount between 0% and 100%. The amount parameter decreases the HSL saturation by that percent.
  11. opacify($color, $amount): This method creates a more opaque color with the amount between 0 and 1. The amount parameter increases the alpha channel by that amount.
  12. V: This method creates a more opaque color with the amount between 0 and 1. The amount parameter increases the alpha channel by that amount.
  13. transparentize($color, $amount): This method creates a more transparent color with the amount between 0 and 1. The amount parameter decreases the alpha channel by that amount.
  14. fade-out($color, $amount): This method creates a more transparent color with the amount between 0 and 1. The amount parameter decreases the alpha channel by that amount.
CSS