<hex-color>

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.

CSS 数据类型 <hex-color> 为描述 sRGB 颜色的十六进制颜色语法的记号,此记号将颜色的主分量(红、绿、蓝)及其透明度写为十六进制数。

在可使用 <color> 的任意位置均可使用 <hex-color> 值。

语法

#RGB        // 三值语法
#RGBA       // 四值语法
#RRGGBB     // 六值语法
#RRGGBBAA   // 八值语法

取值

RRR

颜色的红色分量,为介于 0ff(255)之间不区分大小写的十六进制数。若仅有一数,则重复此数——1 意为 11

GGG

颜色的绿色分量,为介于 0ff(255)之间不区分大小写的十六进制数。若仅有一数,则重复此数——c 意为 cc

BBB

颜色的蓝色分量,为介于 0ff(255)之间不区分大小写的十六进制数。若仅有一数,则重复此数——9 意为 99

AAA 可选

颜色的 alpha 分量,标示其透明度,为介于 0ff(255)之间不区分大小写的十六进制数。若仅有一数,则重复此数——e 意为 ee0(即 00)表示完全透明的颜色,而 f(即 ff)表示完全不透明的颜色。

备注: 此语法不区分大小写——#00ff00#00FF00 相同。

示例

完全不透明的亮粉色的十六进制语法

HTML

html
<span>
  #f09
  <div class="c1"></div>
</span>
<span>
  #F09
  <div class="c2"></div>
</span>
<span>
  #ff0099
  <div class="c3"></div>
</span>
<span>
  #FF0099
  <div class="c4"></div>
</span>

CSS

css
div {
  width: 40px;
  height: 40px;
}
.c1 {
  background: #f09;
}
.c2 {
  background: #f09;
}
.c3 {
  background: #ff0099;
}
.c4 {
  background: #ff0099;
}

结果

规范

Specification
CSS Color Module Level 4
# hex-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
RGB hexadecimal notation (#RRGGBB, #RGB, …)
RGBA hexadecimal notation (#RRGGBBAA, #RGBA)

Legend

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

Full support
Full support

参见

  • <color>——颜色数据类型
  • rgb()——允许用十进制值设置颜色的三个分量及其透明度的函数