CSS background-color 语法
在 CSS 中,background-color 属性用于定义元素的背景颜色。
语法:
background-color: 颜色值;说明:
background-color 属性的取值是一个颜色值,包括以下几种情况(常用的是前 4 种)。
- 关键字,比如 red、orange、skyblue 等。
- 十六进制值,比如 #F1F1F1。
- RGB 值,比如 rgb(255, 255, 255)。
- RGBA 值,比如 rgba(255, 255, 255, 1.0)。
- HSL 值,比如 hsl(60deg 75% 45%)。
- HSLA 值,比如 hsla(60deg 75% 45% / 60%)。
- HWB 值,比如 hwb(120deg 0% 50% / 75%)。
对于 background-color 属性,我们要清楚以下 2 点。
- background-color 会在 background-image 下方显示(如果设置了背景图像)。
- background-color 会填充元素的内边距、边框和内容区域。
提示:
- color 属性定义的是前景色(文本颜色),而 background-color 属性定义的是背景色。
- background-color 还有 2 种特殊取值:① transparent,表示透明;② currentcolor,表示使用当前元素 color 的值。
CSS background-color 摘要
| 属于 | CSS 背景颜色 |
|---|---|
| 使用频率 | 高 |
| 是否继承 | 否 |
| 默认值 | transparent |
| 兼容性 | 查看 |
| 官方文档 | 查看 |
| MDN | 查看 |
CSS background-color 示例
接下来,我们通过几个简单的例子来讲解一下 CSS background-color 属性是如何使用的。
示例 1:background-color 取值为 “关键字”
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 150px;
height: 30px;
}
div:nth-of-type(1) { background-color: red; }
div:nth-of-type(2) { background-color: green; }
div:nth-of-type(3) { background-color: blue; }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>页面效果如下图所示。

示例 2:background-color 取值为 “十六进制值”
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 150px;
height: 30px;
}
div:nth-of-type(1) { background-color: #03FCA1; }
div:nth-of-type(2) { background-color: #048C02; }
div:nth-of-type(3) { background-color: #CE0592; }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>页面效果如下图所示。

示例 3:background-color 取值为 “RGB 值”
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 150px;
height: 30px;
}
div:nth-child(1) { background-color: rgb(249, 175, 56); }
div:nth-child(2) { background-color: rgb(10, 191, 116); }
div:nth-child(3) { background-color: rgb(155, 38, 222); }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>页面效果如下图所示。

示例 4:background-color 取值为 “RGBA 值”
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 150px;
height: 30px;
}
div:nth-child(1) { background-color: rgba(249, 175, 56, 0.8); }
div:nth-child(2) { background-color: rgba(10, 191, 116, 0.8); }
div:nth-child(3) { background-color: rgba(155, 38, 222, 0.8); }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>页面效果如下图所示。

颜色相关属性
在 CSS 中,与颜色相关的属性有很多,如下表所示。
| 属性 | 说明 |
|---|---|
| color | 文本颜色 |
| background-color | 背景颜色 |
| border-color | 边框颜色 |
| outline-color | 轮廓颜色 |
| text-decoration-color | 装饰线颜色 |
| text-emphasis-color | 强调颜色 |
