本文转自Action


日常打卡,CSS 基础第二部分:颜色和背景属性。主要介绍了如何使用 CSS 样式设置元素的颜色、背景颜色和背景图像。

CSS 基础——颜色和背景属性

1、颜色属性 color

color属性用来设置指定元素的颜色,颜色值是一个关键字或一个 16 进制的 RGB 值。 语法:

1
color: 颜色的取值

说明: 关键字就是颜色的英文名称,如redgreenblue分别表示红、绿、蓝。 用 16 进制数来设置颜色,是因为 16 进制数正好能表达 0 到 255 的数值。使用此种方法可以设置 1677 万种颜色。在完全表示颜色的时候使用#加上 16 进制数即可,如下所示:

1
2
3
color: #ff00000 /*表示红色*/
color: #0000ff /*表示蓝色*/
color: #ffff00 /*表示黄色*/

举例:

1
2
3
4
5
.gh {
    font-family: "宋体";
    font-size: 12px;
    color: #9900ff;
}

2、背景颜色 background-color

在 HTML 种,利用 body 的bgcolor属性可以设置网页的背景颜色,而在 CSS 种使用background-color属性不但可以设置网页的颜色,还可以设置文字的背景颜色。 语法:

1
background-color: 颜色的取值

举例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
.gh {
    font-family: "宋体";
    font-size: 12px;
    color: #9900ff;
    backgroud-color: #ff99ff
}

body {
    backgroud-color: #ff99cc;
}

说明: 此段代码种首先定义了gh标记中的背景颜色属性backgroud-color#ff99ff,然后利用body {backgroud-color: #ff99cc;}定义了整个网页的背景颜色。注意事项:这里gh 是类选择器,需要前面加.,而 body 是标签,不需要在前面加.

3、背景图像 backgroud-image

使用backgroud-image属性可以设置元素的背景图像。 语法:

1
background-image: url(图像地址)

说明:

图像地址可以是绝对地址,也可以是相对地址。

举例:

1
2
3
4
5
.l {
    font-family: "宋体";
    font-size: 12px;
    background-image: url(imager/ber.gif)
}

4、背景重复 backgroud-repeat

使用backgroud-repeat属性可以设置背景图像是否平铺,并且可以设置如何平铺。

语法:

1
background-repeat: 取值

说明:

no-repeat表示背景图像不平铺;repeat表示背景图像平铺排满整个网页;repeat-x表示背景图像只在水平方向上平铺;repeat-y表示背景图像只在垂直方向上平铺。

举例:

1
2
3
4
5
6
.l {
    font-family: "宋体";
    font-size: 12px;
    background-image: url(imager/ber_12.gif);
    background-repeat: no-repeat;
}

5、背景附件 background-attachment

使用背景附件属性background-attachment可以设置背景图像时随对象滚动还是固定不动。

语法:

1
background-attachment: acoll/fixed

说明:

scroll表示图像随对象滚动而滚动,是默认选项;fixed表示背景图像固定在页面上不动,只有其他的内容随滚动条滚动。

举例:

1
2
3
4
5
6
.g {
    font-family: "宋体";
    font-size:12px;
    background-image: url(imager/ba_down.jpg);
    background-repeat: no-repeat;
}

6、背景位置 background-position

背景位置属性用于设置背景图像的位置,这个属性只能应用于块级元素和替换元素。替换元素包括imginputtextareaselcet、和object

语法:

1
background-position: 位置的取值

说明:

语法中的取值包括两种,一种是采用数字,另一种是关键字描述。 background-position 属性长度设置值

设置值 说明
X(数值) 设置网页的横向位置,其单位可以是所有尺寸单位
Y(数值) 设置网页的纵向位置,其单位可以是所有尺寸单位

background-position 属性的百分比设置值

设置值 说明
0% 0% 左上位置
50% 0% 靠上居中位置
100% 0% 右上位置
0% 50% 靠左居中位置
50% 50% 正中位置
100% 50% 靠右居中位置
0% 100% 左下位置
50% 100% 靠下居中位置
100% 100% 右下位置

background-position 属性的关键字设置值

设置值 说明
Top left 左上位置
Top center 靠上居中位置
Top right 右上位置
Top center 靠左居中位置
Center center 正中位置
Right center 靠右居中对齐
Bottom left 左下位置
Bottom center 靠下居中对齐
Bottom right 右下位置

举例:

1
2
3
4
5
6
7
8
.g {
    font-family: "宋体"
    font-size: 12px;
    background-attachment: fixed;
    background-image: url(images/img.gif);
    background-position: left top;
    background-repeat: no-repeat;
}

7、背景复合属性 background

使用背景符合属性background可以简化 CSS 代码。

语法:

1
background: 取值

说明:

取值范围可以包括背景颜色、背景图像、背景重复、背景附件和背景位置,各值之间用空格相连。

举例:

1
2
3
4
5
.ds {
    font-family: "宋体";
    font-size: 12px;
    background: url(imgaes/bg_down.jpg) no-repeat left top;
}