此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
background-color
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
background-colorCSS 属性设置元素的背景色。
In this article
尝试一下
background-color: brown;background-color: #74992e;background-color: rgb(255, 255, 128);background-color: rgba(255, 255, 128, 0.5);background-color: hsl(50, 33%, 25%);background-color: hsla(50, 33%, 25%, 0.75);<section> <div></div></section>#example-element { min-width: 100%; min-height: 100%; padding: 10%;}语法
css
/* 关键字值 */background-color: red;background-color: indigo;/* 十六进制值 */background-color: #bbff00; /* 完全不透明 */background-color: #bf0; /* 完全不透明简写 */background-color: #11ffee00; /* 完全透明 */background-color: #1fe0; /* 完全透明简写 */background-color: #11ffeeff; /* 完全不透明 */background-color: #1fef; /* 完全不透明简写 *//* RGB 值 */background-color: rgb(255 255 128); /* 完全不透明 */background-color: rgb(117 190 218 / 50%); /* 50% 透明 *//* HSL 值 */background-color: hsl(50 33% 25%); /* 完全不透明 */background-color: hsl(50 33% 25% / 75%); /* 75% 不透明,25% 透明 *//* 特殊关键字值 */background-color: currentcolor;background-color: transparent;/* 全局值 */background-color: inherit;background-color: initial;background-color: revert;background-color: revert-layer;background-color: unset;background-color 属性被指定为<color> 类型的单值。
值
<color>背景色的统一颜色。它在指定的任何
background-image后面渲染,尽管颜色仍然可以通过图像中任何透明的地方看到。
无障碍
有一点很重要,要确保文本颜色与文本所在背景之间的对比度足够高,以便低视力的人群能够阅读页面内容。
颜色的对比度是通过比较文本和背景颜色值的亮度确定的。要符合当前的Web 内容无障碍指南(WCAG),文本至少要有 4.5:1 的比例,大文本(比如标题)至少要有 3:1 的比例。具有加粗和至少 18.66px 大小,或者具有至少 24px 大小的文本称为大文本。
形式定义
| 初始值 | transparent |
|---|---|
| 适用元素 | 所有元素. It also applies to::first-letter and::first-line. |
| 是否是继承属性 | 否 |
| 计算值 | 颜色计算值 |
| 动画类型 | acolor |
形式语法
background-color =
<color>
示例
>着色盒
此示例演示了如何使用不同的 CSS<color> 值将background-color 应用于 HTML<div> 元素。
HTML
html
<div>他同意自己会受苦。</div><div>他同意自己会受苦。</div><div>他同意自己会受苦。</div>CSS
css
.exampleone { background-color: transparent;}.exampletwo { background-color: rgb(153 102 153); color: rgb(255 255 204);}.examplethree { background-color: #777799; color: #ffffff;}结果
着色表
此示例演示了如何使用<tr> 行和<td> 单元格将background-color 应用于 HTML<table> 元素。
HTML
html
<table> <tr> <td>11</td> <td>12</td> <td>13</td> </tr> <tr> <td>21</td> <td>22</td> <td>23</td> </tr> <tr> <td>31</td> <td>32</td> <td>33</td> </tr></table>CSS
css
table { border-collapse: collapse; border: solid black 1px; width: 250px; height: 150px;}td { border: solid 1px black;}#r1 { background-color: lightblue;}#c12 { background-color: cyan;}#r2 { background-color: grey;}#r3 { background-color: olive;}结果
规范
| Specification |
|---|
| CSS Backgrounds and Borders Module Level 3> # background-color> |