<color>

Sumário

O tipo de dado CSS <color> indica uma cor no espaço sRGB. Uma cor pode ser descrita em qualquer uma destas formas:

Observe que a lista de valores de cores aceitas foi estendida à medida que a especificação evoluiu, culminando com as cores CSS3 mais recentes.

Associado à cor no espaço sRGB, um valor <color> também pode consistir de uma coordenada de valor de transparência canal-alfa, Indicando como a cor deve se composta com sua cor de fundo.

Embora os valores de cores CSS sejam definidos com precisão, eles podem aparecer de forma diferente em dispositivos de saída diferentes. A maioria deles não está calibrada e alguns navegadores não suportam o perfil de cores dos dispositivos de saída. Sem estes, a renderização de cores pode variar muito.

Nota: A recomendação WCAG 2.0 do W3C aconselha fortemente aos autores web não usarem cor como o único meio para transmitir uma mensagem específica, ação ou resultado. Alguns usuários têm problemas em distinguir cores e as informações transmitidas podem não ser compreendidas. Claro, isso não impede o uso da cor, mas o seu uso apenas como o único meio para descrever certas coisas (veja Cor e contraste de cor (en-US) para mais informações).

Interpolação

Valores do tipo de dados CSS <color> podem ser interpolados para realizar animações ou para criar valores <gradient>. Nesse caso, eles são interpolados em cada um de seus componentes vermelho, verde, azul, cada um manipulado como um número real, de ponto flutuante. Observe que a interpolação de cores ocorre no espaço de cores sRGBA alfa-pré-multiplicado para evitar que cores cinzentas inesperadas apareçam. Nas animações, a velocidade da interpolação é determinada pela função de temporização (en-US) associada à animação.

Valores

Existem várias maneiras de descrever um valor <color>.

Palavras-chave de cores

As palavras-chave de cor são identificadores não sensíveis a maiúsculas e minúsculas que representam uma cor específica, ex.: red, blue, brown, ou lightseagreen. O nome descreve a cor, embora seja principalmente artificial. A lista de valores aceitos variou muito ao longo das diferentes especificações:

  • CSS nível 1 aceita apenas16 cores básicas, denominadas cores VGA já que foram tiradas do conjunto de cores exibíveis das placas gráficas VGA.
  • CSS nível 2 Adicionou a palavra-chave orange.
  • Desde o início, os navegadores aceitaram outras cores, principalmente a lista de cores nomeadas X11 já que alguns dos primeiros navegadores foram aplicações X11, embora com algumas diferenças. O SVG 1.0 foi o primeiro padrão a definir formalmente essas palavras-chave; As cores no CSS nível 3 também formalmente definiram essas palavras-chave. Elas são muitas vezes referidas como palavras-chave de cor estendida, cores X11 ou cores SVG.

Existem algumas restrições a serem consideradas ao usar palavras-chave:

  • Com exceção das 16 cores básicas comuns com HTML, as outras não podem ser usadas em HTML. O HTML vai converter esses valores desconhecidos com um algoritmo específico levando a cores completamente diferentes. Essas palavras-chave só devem ser usadas em SVG & CSS.
  • Palavras-chave desconhecidas tornam a propriedade CSS inválida. Propriedades inválidas sendo ignoradas, a cor não terá efeito. Esse é um comportamento diferente do HTML.
  • Nenhuma palavra-chave de core definida em CSS têm qualquer transparência — eles são cores simples, sólidas.
  • Várias palavras-chave indicam as mesmas cores:
    • darkgray / darkgrey
    • darkslategray / darkslategrey
    • dimgray / dimgrey
    • lightgray / lightgrey
    • lightslategray / lightslategrey
    • gray / grey
    • slategray / slategrey
  • Embora os nomes das palavras-chave tenham sido tomadas pelos nomes de cores X11 habituais, a cor pode divergir da cor do sistema correspondente em sistemas X11 como estes são adaptados para o hardware específico pelo fabricante.
Especificação Cor Palavra-chave valores hex RGB Resultado
CSS Level 1 black #000000
silver #c0c0c0
gray #808080
white #ffffff
maroon #800000
red #ff0000
purple #800080
fuchsia #ff00ff
green #008000
lime #00ff00
olive #808000
yellow #ffff00
navy #000080
blue #0000ff
teal #008080
aqua #00ffff
CSS Level 2 (Revision 1) orange #ffa500
CSS Color Module Level 3 aliceblue #f0f8ff
antiquewhite #faebd7
aquamarine #7fffd4
azure #f0ffff
beige #f5f5dc
bisque #ffe4c4
blanchedalmond #ffebcd
blueviolet #8a2be2
brown #a52a2a
burlywood #deb887
cadetblue #5f9ea0
chartreuse #7fff00
chocolate #d2691e
coral #ff7f50
cornflowerblue #6495ed
cornsilk #fff8dc
crimson #dc143c
cyan #00ffff
darkblue #00008b
darkcyan #008b8b
darkgoldenrod #b8860b
darkgray #a9a9a9
darkgreen #006400
darkgrey #a9a9a9
darkkhaki #bdb76b
darkmagenta #8b008b
darkolivegreen #556b2f
darkorange #ff8c00
darkorchid #9932cc
darkred #8b0000
darksalmon #e9967a
darkseagreen #8fbc8f
darkslateblue #483d8b
darkslategray #2f4f4f
darkslategrey #2f4f4f
darkturquoise #00ced1
darkviolet #9400d3
deeppink #ff1493
deepskyblue #00bfff
dimgray #696969
dimgrey #696969
dodgerblue #1e90ff
firebrick #b22222
floralwhite #fffaf0
forestgreen #228b22
gainsboro #dcdcdc
ghostwhite #f8f8ff
gold #ffd700
goldenrod #daa520
greenyellow #adff2f
grey #808080
honeydew #f0fff0
hotpink #ff69b4
indianred #cd5c5c
indigo #4b0082
ivory #fffff0
khaki #f0e68c
lavender #e6e6fa
lavenderblush #fff0f5
lawngreen #7cfc00
lemonchiffon #fffacd
lightblue #add8e6
lightcoral #f08080
lightcyan #e0ffff
lightgoldenrodyellow #fafad2
lightgray #d3d3d3
lightgreen #90ee90
lightgrey #d3d3d3
lightpink #ffb6c1
lightsalmon #ffa07a
lightseagreen #20b2aa
lightskyblue #87cefa
lightslategray #778899
lightslategrey #778899
lightsteelblue #b0c4de
lightyellow #ffffe0
limegreen #32cd32
linen #faf0e6
mediumaquamarine #66cdaa
mediumblue #0000cd
mediumorchid #ba55d3
mediumpurple #9370db
mediumseagreen #3cb371
mediumslateblue #7b68ee
mediumspringgreen #00fa9a
mediumturquoise #48d1cc
mediumvioletred #c71585
midnightblue #191970
mintcream #f5fffa
mistyrose #ffe4e1
moccasin #ffe4b5
navajowhite #ffdead
oldlace #fdf5e6
olivedrab #6b8e23
orangered #ff4500
orchid #da70d6
palegoldenrod #eee8aa
palegreen #98fb98
paleturquoise #afeeee
palevioletred #db7093
papayawhip #ffefd5
peachpuff #ffdab9
peru #cd853f
pink #ffc0cb
plum #dda0dd
powderblue #b0e0e6
rosybrown #bc8f8f
royalblue #4169e1
saddlebrown #8b4513
salmon #fa8072
sandybrown #f4a460
seagreen #2e8b57
seashell #fff5ee
sienna #a0522d
skyblue #87ceeb
slateblue #6a5acd
slategray #708090
slategrey #708090
snow #fffafa
springgreen #00ff7f
steelblue #4682b4
tan #d2b48c
thistle #d8bfd8
tomato #ff6347
turquoise #40e0d0
violet #ee82ee
wheat #f5deb3
whitesmoke #f5f5f5
yellowgreen #9acd32
CSS Color Module Level 4 rebeccapurple #663399

A cor rebeccapurple é equivalente à cor #639, e mais informações sobre por que foi introduzida pode ser encontrada neste post no blog Codepen por Trezy "Honoring a Great Man" (em inglês)

palavra-chave transparent

A palavra-chave transparent representa uma cor totalmente transparente, isto é, a cor vista será a cor de fundo. Tecnicamente, é um preto com canal alfa no seu valor mínimo e é um atalho para rgba(0,0,0,0).

Nota: Nota histórica A palavra-chave transparent não era uma cor verdadeira no CSS nível 2 (Revisão 1). Era uma palavra-chave específica que poderia ser usada no lugar de um valor <color> regular em duas propriedades CSS: background e border (en-US). Ela foi adicionada essencialmente para permitir a substituição de cores sólidas herdadas.

Com o apoio da opacidade através de canais alfal, transparent foi redefinida como uma cor verdadeira no Cores CSS nível 3 permitindo seu uso em qualquer lugar onde for exigido um valor para <color>, como a propriedade color.

palavra-chave currentcolor

A palavra-chave currentcolor representa o valor calculado da propriedade color dos elementos . Ela permite que as propriedades de cor sejam herdadas por propriedades ou propriedades de elemento filho que não a herdam por padrão.

Ela também pode ser usada em propriedades que herdam o valor calculado da propriedade color do elemento e será equivalente à palavra-chave inherit nesses elementos, se houver.

Exemplo ao vivo

A cor da linha (uma div preenchida com cor) se adapta à cor de sua propriedade color, herdada de seu pai.

Exemplo 1
html
<div style="color:darkred">
  A cor deste texto é a mesma da linha:
  <div style="background:currentcolor; height:1px"></div>
  Mais algum texto.
</div>
Exemplo 2
html
<div style="color:blue; border-bottom: 1px dashed currentcolor;">
  A cor deste texto é a mesma da linha:
  <div style="background:currentcolor; height:1px"></div>
  Mais algum texto.
</div>

rgb()

Nota: Na especificação Módulo de cor CSS Color nível 4, a rgba() foi definida como uma função herdada com gramática e comportamento idênticos à rgb(); na verdade, um apelido. Mais para frente, ambas podem aceitar exatamente os mesmos parâmetros.

RGB colors can be expressed through both hexadecimal (prefixed with #) and functional (rgb(), rgba()) notations.

Hexadecimal notation (en-US): #RGB[A] or#RRGGBB[AA]

R (red), G (green), B (blue), and A (alpha) are hexadecimal characters (0–9, A–F). A is optional. For example, #ff0000 is equivalent to #ff0000ff. The three-digit notation (#RGB) is a shorter version of the six-digit form (#RRGGBB). For example, #f09 is the same color as #ff0099. Likewise, the four-digit RGB notation (#RGBA) is a shorter version of the eight-digit form (#RRGGBBAA). For example, #0f38 is the same color as #00ff3388.

rgb() (en-US) or rgba() (en-US): rgb[a](R, G, B[, A]) or rgb[a](R G B[ / A])

R (red), G (green), and B (blue) can be either <number>s or <percentage> (en-US)s, where the number 255 corresponds to 100%. A (alpha) can be a <number> between 0 and 1, or a <percentage> (en-US), where the number 1 corresponds to 100% (full opacity).

/* These examples all specify the same RGB color: */

#f03
#F03
#ff0033
#FF0033
rgb(255,0,51)
rgb(255, 0, 51)
rgb(255, 0, 51.2) /* ERROR! Don't use fractions, use integers */
rgb(100%,0%,20%)
rgb(100%, 0%, 20%)
rgb(100%, 0, 20%) /* ERROR! Don't mix up integer and percentage notation */

/* whitespace syntax */
rgb(255 0 0)

/* optional alpha value */
rgb(255,0,0,0.4)  /* 40% opaque red */
rgb(255,0,0,40%)  /* 40% opaque red with percentage value for alpha */
rgb(255 0 0 / 0.4)  /* 40% opaque red */
rgb(255 0 0 / 40%)  /* 40% opaque red with percentage value for alpha */

hsl()

Nota: In the CSS Color Module Level 4 spec, hsla() has been defined as a legacy function with identical grammar and behaviour to hsl(); in effect, an alias. Going forward, both can accept exactly the same parameters.

Colors can also be defined via hue, saturation, and lightness, or HSL, by using the hsl() functional notation. The advantage of HSL over RGB is that it is far more intuitive: you can guess at the colors you want, and then tweak. It is also easier to create sets of matching colors (by keeping the hue the same and varying the lightness/darkness, and saturation).

Hue is represented as an angle of the color circle (i.e. the rainbow represented in a circle). This angle is given as a unitless <number>. By definition red=0=360, and the other colors are spread around the circle, so green=120, blue=240, etc. As an angle, it implicitly wraps around such that -120=240 and 480=120.

Saturation and lightness are represented as percentages. 100% is full saturation, and 0% is a shade of grey. 100% lightness is white, 0% lightness is black, and 50% lightness is "normal."

css
hsl(0,  100%,50%)    /* red */
hsl(30, 100%,50%)
hsl(60, 100%,50%)
hsl(90, 100%,50%)
hsl(120,100%,50%)    /* green */
hsl(150,100%,50%)
hsl(180,100%,50%)
hsl(210,100%,50%)
hsl(240,100%,50%)    /* blue */
hsl(270,100%,50%)
hsl(300,100%,50%)
hsl(330,100%,50%)
hsl(360,100%,50%)    /* red */

hsl(120,100%,25%)    /* dark green */
hsl(120,100%,50%)    /* green */
hsl(120,100%,75%)    /* light green */

hsl(120,100%,50%)    /* green */
hsl(120, 67%,50%)
hsl(120, 33%,50%)
hsl(120,  0%,50%)

hsl(120, 60%,70%)    /* pastel green */

/* whitespace syntax */
hsl(120 60% 70%)  /* pastel green */

/* angle values for hue component; also accepts rad, grad, turn */
hsl(120deg 60% 70%)  /* pastel green */

/* optional alpha value */
hsl(240,100%,50%,0.05)  /* 5% opaque blue */
hsl(240,100%,50%,5%)  /* 5% opaque blue with percentage value for alpha */
hsl(240 100% 50% / 0.05) /* 5% opaque blue */
hsl(240 100% 50% / 5%) /* 5% opaque blue with percentage value for alpha */

rgba()

RGB colors can be expressed through both hexadecimal (prefixed with #) and functional (rgb(), rgba()) notations.

Hexadecimal notation (en-US): #RGB[A] or#RRGGBB[AA]

R (red), G (green), B (blue), and A (alpha) are hexadecimal characters (0–9, A–F). A is optional. For example, #ff0000 is equivalent to #ff0000ff. The three-digit notation (#RGB) is a shorter version of the six-digit form (#RRGGBB). For example, #f09 is the same color as #ff0099. Likewise, the four-digit RGB notation (#RGBA) is a shorter version of the eight-digit form (#RRGGBBAA). For example, #0f38 is the same color as #00ff3388.

rgb() (en-US) or rgba() (en-US): rgb[a](R, G, B[, A]) or rgb[a](R G B[ / A])

R (red), G (green), and B (blue) can be either <number>s or <percentage> (en-US)s, where the number 255 corresponds to 100%. A (alpha) can be a <number> between 0 and 1, or a <percentage> (en-US), where the number 1 corresponds to 100% (full opacity).

css
#f030                /* 0% opaque red */
#F03F                /* full opaque red */
#ff003300            /* 0% opaque red */
#FF003388            /* 50% opaque red */
rgba(255,0,0,0.1)    /* 10% opaque red */
rgba(255,0,0,0.4)    /* 40% opaque red */
rgba(255,0,0,0.7)    /* 70% opaque red */
rgba(255,0,0,  1)    /* full opaque red */

/* whitespace syntax */
rgba(255 0 0 / 0.4)  /* 40% opaque red */

/* percentage value for alpha */
rgba(255 0 0 / 40%)  /* 40% opaque red */

Nota: In the CSS Color Module Level 4 spec, rgba() has been defined as a legacy function with identical grammar and behaviour to rgb(); in effect, an alias. Going forward, both can accept exactly the same parameters.

hsla()

Colors can be defined in the hue-saturation-lightness-alpha model (HSLa) using the hsla() functional notation. HSLa extends the HSL color model to include the alpha channel, allowing specification of the opacity of a color. a means opacity: 0=transparent; 1=opaque;

css
hsla(240,100%,50%,0.05)   /* 5% opaque blue */
hsla(240,100%,50%, 0.4)   /* 40% opaque blue */
hsla(240,100%,50%, 0.7)   /* 70% opaque blue */
hsla(240,100%,50%,   1)   /* full opaque blue */

/* whitespace syntax */
hsla(240 100% 50% / 0.05) /* 5% opaque blue */

/* percentage value for alpha */
hsla(240 100% 50% / 5%) /* 5% opaque blue */

/* angle values for hue component; also accepts rad, grad, turn */
hsla(240deg 100% 50% / 5%) /* 5% opaque blue */
hsla(240deg,100%,50%, 0.4)  /* 40% opaque blue */

Nota: In the CSS Color Module Level 4 spec, hsla() has been defined as a legacy function with identical grammar and behaviour to hsl(); in effect, an alias. Going forward, both can accept exactly the same parameters.

System Colors

Not all system colors are supported on all systems. Deprecated for use on public web pages.

ActiveBorder

Active window border.

ActiveCaption

Active window caption. Should be used with CaptionText as foreground color.

AppWorkspace

Background color of multiple document interface.

Background

Desktop background.

ButtonFace

Face background color for 3-D elements that appear 3-D due to one layer of surrounding border. Should be used with the ButtonText foreground color.

ButtonHighlight

The color of the border facing the light source for 3-D elements that appear 3-D due to that layer of surrounding border.

ButtonShadow

The color of the border away from the light source for 3-D elements that appear 3-D due to that layer of surrounding border.

ButtonText

Text on push buttons. Should be used with the ButtonFace or ThreeDFace background color.

CaptionText

Text in caption, size box, and scrollbar arrow box. Should be used with the ActiveCaption background color.

GrayText

Grayed (disabled) text.

Highlight

Item(s) selected in a control. Should be used with the HighlightText foreground color.

HighlightText

Text of item(s) selected in a control. Should be used with the Highlight background color.

InactiveBorder

Inactive window border.

InactiveCaption

Inactive window caption. Should be used with the InactiveCaptionText foreground color.

InactiveCaptionText

Color of text in an inactive caption. Should be used with the InactiveCaption background color.

InfoBackground

Background color for tooltip controls. Should be used with the InfoText foreground color.

InfoText

Text color for tooltip controls. Should be used with the InfoBackground background color.

Menu background. Should be used with the MenuText or -moz-MenuBarText foreground color.

Text in menus. Should be used with the Menu background color.

Scrollbar

Background color of scroll bars.

ThreeDDarkShadow

The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.

ThreeDFace

The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Should be used with the ButtonText foreground color.

ThreeDHighlight

The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.

ThreeDLightShadow

The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.

ThreeDShadow

The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.

Window

Window background. Should be used with the WindowText foreground color.

WindowFrame

Window frame.

WindowText

Text in windows. Should be used with the Window background color.

Mozilla System Color Extensions

  • -moz-ButtonDefault
    • : The border color that goes around buttons that represent the default action for a dialog box.
  • -moz-ButtonHoverFace
    • : The background color of a button that the mouse pointer is over (which would be ThreeDFace or ButtonFace when the mouse pointer is not over it). Should be used with the -moz-ButtonHoverText foreground color.
  • -moz-ButtonHoverText
    • : The text color of a button that the mouse pointer is over (which would be ButtonText when the mouse pointer is not over it). Should be used with the -moz-ButtonHoverFace background color.
  • -moz-CellHighlight
    • : Background color for selected item in a tree widget. Should be used with the -moz-CellHighlightText foreground color. See also -moz-html-CellHighlight.
  • -moz-CellHighlightText
    • : Text color for a selected item in a tree. Should be used with the -moz-CellHighlight background color. See also -moz-html-CellHighlightText.
  • -moz-Combobox
    • : Background color for combo-boxes. Should be used with the -moz-ComboboxText foreground color. In versions prior to 1.9.2, use -moz-Field instead.
  • -moz-ComboboxText
    • : Text color for combo-boxes. Should be used with the -moz-Combobox background color. In versions prior to 1.9.2, use -moz-FieldText instead.
  • -moz-Dialog
    • : Background color for dialog boxes. Should be used with the -moz-DialogText foreground color.
  • -moz-DialogText
    • : Text color for dialog boxes. Should be used with the -moz-Dialog background color.
  • -moz-dragtargetzone -moz-EvenTreeRow
    • : Background color for even-numbered rows in a tree. Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field. See also -moz-OddTreeRow.
  • -moz-Field
    • : Text field background color. Should be used with the -moz-FieldText foreground color.
  • -moz-FieldText
    • : Text field text color. Should be used with the -moz-Field, -moz-EvenTreeRow, or -moz-OddTreeRow background color.
  • -moz-html-CellHighlight
    • : Background color for highlighted item in HTML <select>s. Should be used with the -moz-html-CellHighlightText foreground color. Prior to Gecko 1.9, use -moz-CellHighlight.
  • -moz-html-CellHighlightText
    • : Text color for highlighted items in HTML <select>s. Should be used with the -moz-html-CellHighlight background color. Prior to Gecko 1.9, use -moz-CellHighlightText.
  • -moz-mac-accentdarkestshadow -moz-mac-accentdarkshadow -moz-mac-accentface -moz-mac-accentlightesthighlight -moz-mac-accentlightshadow -moz-mac-accentregularhighlight -moz-mac-accentregularshadow -moz-mac-chrome-active
  • -moz-mac-chrome-inactive
  • -moz-mac-focusring -moz-mac-menuselect -moz-mac-menushadow -moz-mac-menutextselect -moz-MenuHover
    • : Background color for hovered menu items. Often similar to Highlight. Should be used with the -moz-MenuHoverText or -moz-MenuBarHoverText foreground color.
  • -moz-MenuHoverText
    • : Text color for hovered menu items. Often similar to HighlightText. Should be used with the -moz-MenuHover background color.
  • -moz-MenuBarText
    • : Text color in menu bars. Often similar to MenuText. Should be used on top of Menu background.
  • -moz-MenuBarHoverText
    • : Color for hovered text in menu bars. Often similar to -moz-MenuHoverText. Should be used on top of -moz-MenuHover background.
  • -moz-nativehyperlinktext
    • : Default platform hyperlink color.
  • -moz-OddTreeRow
    • : Background color for odd-numbered rows in a tree. Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field. See also -moz-EvenTreeRow.
  • -moz-win-communicationstext
  • -moz-win-mediatext

Mozilla Color Preference Extensions

-moz-activehyperlinktext

User's preference for text color of active links. Should be used with the default document background color.

-moz-default-background-color

User's preference for the document background color.

-moz-default-color

User's preference for the text color.

-moz-hyperlinktext

User's preference for the text color of unvisited links. Should be used with the default document background color.

-moz-visitedhyperlinktext

User's preference for the text color of visited links. Should be used with the default document background color.

Specificações

Specification
CSS Color Module Level 4
# color-syntax

Compatibilidade com navegadores

BCD tables only load in the browser

Ver também