Don’t hesitate to contact us if you have any feedback.

SCSS – Convert HEX to HSL

Manipulating colors in web design is a common task, and sometimes you need to convert color formats to achieve the desired effect or compatibility. The SCSS function hexTohslString provides a straightforward way to convert a hexadecimal color value to an HSL (Hue, Saturation, Lightness) string, which can then be used within your stylesheets.

The Code

@use 'sass:color';

@function hexTohslString($hexColor) {
  $h: color.hue($hexColor);
  $s: color.saturation($hexColor);
  $l: color.lightness($hexColor);

  @return '#{calc($h / 100 * 100)} #{$s} #{$l}';
}

How It Functions

The hexTohslString function performs the following steps:

  1. It takes a hexadecimal color value as an argument ($hexColor).
  2. It uses the built-in SCSS functions hue, saturation, and lightness to extract the respective HSL components from the hexadecimal value.
  3. It constructs an HSL string by embedding the calculated values into a string template. The hue value is wrapped in a calc() function to convert it to a percentage.
  4. The function then returns this HSL string.

Usage Example

In the provided code, the function is used to set a CSS variable --white at the :root level:

:root {
  --color: #{hexTohslString('#FF00FF')};

  // Result
  --color: 300,100%,50%;
}

This variable now holds the HSL equivalent of the magenta color (#FF00FF), which can be used throughout the CSS as a custom property.

Benefits

  • Flexibility: Easily switch between color formats depending on the needs of your project.
  • Readability: HSL is often more human-readable and easier to adjust manually than hexadecimal.
  • Maintainability: Define colors in one format and convert them as needed without manual conversion.

By integrating this function into your SCSS workflow, you can simplify the process of working with different color formats and enhance the maintainability of your stylesheets.
For more insights into a unified approach to color management in SCSS, check out this comprehensive article: SCSS Color Management: A Unified Approach.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *