CSS/tutorials/lesson3

来自开放百科 - 灰狐
2010年10月16日 (六) 02:28Allen (讨论 | 贡献)的版本

跳转到: 导航, 搜索

目录

第3课:颜色与背景

本课,你将学习如何在网站上应用颜色与背景。我们还会介绍用于定位和控制背景图像的高级方法。本课将对下列CSS属性进行讲解:

  • color 前景色
  • background-color 背景色
  • background-image 背景图像
  • background-repeat 平铺背景图像
  • background-attachment 固定背景图像
  • background-position 放置背景图像
  • background 缩写

color

前景色:‘color’属性

CSS属性color用于指定元素的前景色。

例如,假设你要让页面中的所有标题(headline)都显示为深红色,而这些标题采用的都是h1元素,那么可以用下面的代码来实现把h1元素的前景色设为红色。

h1 {
color: #ff0000;
}

Icon-example.gif 显示示例

颜色值可以用十六进制表示(比如上例中的#ff0000),也可以用颜色名称(比如“red”)或RGB值(比如rgb(255,0,0))表示。

background-color

背景色:‘background-color’属性

CSS属性background-color用于指定元素的背景色。

因为body元素包含了HTML文档的所有内容,所以,如果要改变整个页面的背景色的话,那么为body元素应用background-color属性就行了。

你也可以为其他包含标题或文本的元素单独应用背景色。在下例中,我们为body和h1元素分别应用了不同的背景色。

body {
 background-color: #FFCC66;
}
h1 {
 color: #990000;
 background-color: #FC9804;
}

Icon-example.gif 显示示例

注意:我们为h1元素应用了两个CSS属性,它们之间以分号(“;”)分隔。

background-image

背景图像[background-image]

CSS属性background-image用于设置背景图像。

在下面的示例中,我们使用了一张蝴蝶的图像作为背景。你可以将该图片下载下来(方法为:鼠标右击该图片,然后选择“图片另存为”),以便在自己的计算机上使用。当然,你也可以选用其他你觉得满意的图片。

Butterfly.gif

如果要把这个蝴蝶的图片作为网页的背景图像,只要在body元素上应用background-image属性、然后给出蝴蝶图片的存放位置就行了。

body {
 background-color: #FFCC66;
 background-image: url("butterfly.gif");
}
h1 {
 color: #990000;
 background-color: #FC9804;
}

Icon-example.gif 显示示例

注意我们指定图片存放位置的方式:url("butterfly.gif")。这表明图片文件和样式表存放在同一目录下。你也可以引用存放在其他目录的图片,只需给出存放路径即可(比如url("../images/butterfly.gif"));此外,你甚至可以通过给出图片的地址来引用因特网(Internet)上的图片(比如url("butterfly.gif"))。

background-repeat

平铺背景图像[background-repeat]

你有没有发现在上例中那个蝴蝶图片在横向和纵向都被平铺了?CSS属性background-repeat就是用于控制平铺的。

下表概括了background-repeat的四种不同取值。

描述 示例
background-repeat:repeat-x 图像横向平铺 显示示例
background-repeat:repeat-y 图像纵向平铺 显示示例
background-repeat:repeat 图像横向和纵向都平铺 显示示例
background-repeat:no-repeat 图像不平铺 显示示例

例如,为了避免平铺背景图像,代码应该这样:

body {
 background-color: #FFCC66;
 background-image: url("butterfly.gif");
 background-repeat: no-repeat;
}
h1 {
 color: #990000;
 background-color: #FC9804;
}

Icon-example.gif 显示示例

background-attachment

background-position

background

Comment-32x32.png

<discussion>characters_max=300</discussion>

分享您的观点
个人工具
名字空间

变换
操作
导航
工具箱