hsl()

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Some parts of this feature may have varying levels of support.

hsl() 函数标记根据其色相饱和度明度来表达 sRGB 颜色。可选的 alpha 成分代表了颜色的透明度。

备注: 旧版的 hsla() 语法是 hsl() 的别称,接收相同的参数,行为也是相同的。

尝试一下

使用 hsl() 来定义互补色可以用一个公式来完成,因为它们位于色环中同一直径上。如果一个颜色的色相度是 θ,那么其互补色的色相角就是 180deg - θ

语法

css
hsl(120deg 75% 25%)
hsl(120deg 75% 25% / 0.6)

此函数也接受旧版的语法,即所有的值都是用逗号分隔的。

函数标记:hsl(H S L[ / A])

H

<number><angle> 或者关键字 none,代表色相角。关于此类型的更多细节可以参见 <hue> 文档。

S

<percentage> 或者关键字 none,代表饱和度。在这里,100% 是完全饱和,而 0% 是完全不饱和(灰色)。

L

<percentage> 或者关键字 none,代表明度。在这里,100% 是白色,0% 是黑色,50% 是“正常”。

A 可选

<alpha-value> 或者关键字 none,其中数字 1 代表 100%(完全不透明)。

备注: 参见缺失颜色成分 以了解 none 的效果。

形式语法

<hsl()> = 
<legacy-hsl-syntax> |
<modern-hsl-syntax>

<legacy-hsl-syntax> =
hsl( <hue> , <percentage> , <percentage> , <alpha-value>? )

<modern-hsl-syntax> =
hsl( [ <hue> | none ] [ <percentage> | <number> | none ] [ <percentage> | <number> | none ] [ / [ <alpha-value> | none ] ]? )

<hue> =
<number> |
<angle>

<alpha-value> =
<number> |
<percentage>

示例

使用 hsl() 和 conic-gradient()

hsl() 函数和 conic-gradient() 可以很好地配合使用,因为这两个都处理角度。

CSS

css
div {
  width: 100px;
  height: 100px;
  background: conic-gradient(
    hsl(360 100% 50%),
    hsl(315 100% 50%),
    hsl(270 100% 50%),
    hsl(225 100% 50%),
    hsl(180 100% 50%),
    hsl(135 100% 50%),
    hsl(90 100% 50%),
    hsl(45 100% 50%),
    hsl(0 100% 50%)
  );
  clip-path: circle(closest-side);
}

结果

旧版语法:逗号分隔值

由于历史原因,hsl() 函数接受所有值用逗号分隔的形式。

HTML

html
<div class="space-separated"></div>
<div class="comma-separated"></div>

CSS

css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.space-separated {
  background-color: hsl(0 100% 50% / 50%);
}

div.comma-separated {
  background-color: hsl(0, 100%, 50%, 50%);
}

结果

旧版语法:hsla()

旧版的 hsla() 语法是 hsl() 的别称。

HTML

html
<div class="hsl"></div>
<div class="hsla"></div>

CSS

css
div {
  width: 100px;
  height: 50px;
  margin: 1rem;
}

div.hsl {
  background-color: hsl(0 100% 50% / 50%);
}

div.hsla {
  background-color: hsla(0, 100%, 50%, 50%);
}

结果

规范

Specification
CSS Color Module Level 5
# relative-HSL
CSS Color Module Level 4
# the-hsl-notation

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
hsl() (HSL color model)
Alpha parameter
Mix <percentage> and <number> in parameters
Relative HSL colors
Space-separated parameters

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
Has more compatibility info.

参见