Visit Mozilla.org

CSS:Getting Started:Color

From MDC


本页中会讲解更多关于如何在CSS中指定颜色。

我们将为我们的示例样式表引入背景色。

[编辑] 资料: 颜色

我们的教程到目前为止,已经使用过为数不多的几种已命名的颜色。CSS 2 总共支持17种已命名的颜色。有些颜色名称甚至出乎你的意料:

  black   gray   silver   white  
原色 red   lime   blue  
补色 yellow   aqua   fuchsia  
 maroon  orange  olive  purple  green  navy  teal 


更多资料
你的浏览器可能支持更多已命名的颜色,如:
dodgerblue  peachpuff   tan   firebrick   aquamarine  

关于此扩展列表更详细的资料,请参见: CSS 3颜色模型部分的 SVG color keywords. 注意,你使用颜色名称可能读者浏览器并不支持。|}


For a larger palette, specify the red, green and blue components of the color you want by using a number sign (hash) and three hexadecimal digits in the range 0 – 9, a – f. The letters a – f represent the values 10 – 15:

black  #000
pure red   #f00
pure green   #0f0
pure blue   #00f
white   #fff

完整的色板,为每种颜色组成指定两个十六进制数字:

black   #000000
pure red   #ff0000
pure green   #00ff00
pure blue   #0000ff
white   #ffffff

通常你从图形软件或其它工具获得的是6个数字的十六进制代码。

示例
让我们来做一个小练习, 你可以手工调整3个数字的颜色值来达成你的大多数意图:
开始是纯红:  #f00
让它变淡一些,加些绿色和蓝色:  #f77
让它偏向橙色,再加一些绿色:  #fa7
让它暗一些,减少所有组成颜色的数值:  #c74
增加饱和度, 让颜色组成更相等:  #c98
如果你让它们完全相等,你就会得到灰色:  #ccc
一个柔和的阴影如,灰蓝色
开始是纯白色:  #fff
稍微减少其它组成颜色:  #eef


更多资料
还可以使用范围在0– 255内的RGB值或百分比来指定颜色。

示例:这是 maroon (暗红):

rgb(128, 0, 0)


更多关于如何指定颜色的资料,请参见: Colors in the CSS Specification.

更多关于匹配系统颜色如菜单和3d界面的资料,请参见: CSS2 System Colors in the CSS Specification.


[编辑] 颜色属性

我们已经在文本中使用过color属性。

我们也可以使用background-color属性改变元素的背景。

可以通过设置transparent移除所有背景色,显示父元素的背景。

示例
The Example boxes in this tutorial use this pale yellow background:
background-color: #fffff4;

更多资料 框内使用 pale gray:

background-color: #f4f4f4;

[编辑] 实践: 使用颜色代码

编辑你的 CSS 文件。使所有文字显示为粗体,并将每个单词的首字母设置成灰蓝色背景。(你的CSS文件排版与注释可能与下面显示的有些不同。这不影响结果,尽管使用你自己喜欢的排版和注释就行了。)

/*** CSS Tutorial: Color page ***/
 
/* page font */
body {font: 16px "Comic Sans MS", cursive;}
 
/* paragraphs */
p {color: blue;}
#first {font-style: italic;}
 
/* initial letters */
strong {
  color: red;
  background-color: #ddf;
  font: 200% serif;
  }
 
.carrot {color: red;}
.spinach {color: green;}

刷新浏览器,看到如下结果:

Cascading Style Sheets
Cascading Style Sheets


挑战
修改你的CSS文件,在不改变结果的情况下,将所有命名颜色改为3数字颜色代码。

(使用3数字颜色代码也许达不到一模一样的效果,但肯定可以做出相似的效果。要达到完全一样,需要使用6数字颜色代码,匹配的颜色可通过查找CSS规范或在图形工具中查找。)


[编辑] 接下来的内容是什么?

我们的示例文档和示例样式表已经将内容与样式完全分离了。

The next page explains how you can make exceptions to this strict separation: Content