CSS background-color
属性用于设置元素的背景颜色。例如,
h1 {
background-color: orange;
}
浏览器输出

在这里,background-color
属性将 h1
元素的背景颜色设置为橙色。
CSS Background-Color 语法
background-color
属性的语法是:
background-color: color-value | transparent | initial | inherit;
这里,
color-value
:指定背景颜色,例如red
、blue
或rgb(255, 0, 0)
等。transparent
:将背景设置为透明(默认值)。initial
:将属性值设置为默认值。inherit
:继承其父元素的属性值。
示例:CSS background-color
让我们看一个 background-color
属性的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-color</title>
</head>
<body>
<h2>background-color: orange</h2>
<div class="box box1"></div>
<h2>background-color: rgb(0, 0, 255)</h2>
<div class="box box2"></div>
<h2>background-color: #00ff00;</h2>
<div class="box box3"></div>
</body>
</html>
/* styles the div having class box */
div.box {
width: 80%;
height: 100px;
margin: auto;
border: 1px solid black;
}
div.box1 {
background-color: orange;
}
div.box2 {
background-color: rgb(0, 0, 255);
}
div.box3 {
background-color: #00ff00;
}
浏览器输出

上面的示例说明了如何使用不同的颜色格式为 div
元素提供背景颜色。
Background-Color 的可访问性问题
确保背景颜色和文本颜色之间有足够的对比度至关重要。低对比度可能导致可访问性问题,例如眼部疲劳,以及视障人士难以阅读。
让我们看一个例子,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background-color</title>
</head>
<body>
<h1 class="insufficient-contrast">
Insufficient Contrast between text color and background
</h1>
<h1 class="sufficient-contrast">
Sufficient Contrast between text color and background
</h1>
</body>
</html>
/* provides insufficient contrast */
h1.insufficient-contrast {
color: aliceblue;
background-color: white;
}
/*provides sufficient contrast */
h1.sufficient-contrast {
color: black;
background-color: orange;
}
浏览器输出

在上面的示例中,您可以看到背景颜色和文本颜色之间存在对比度很重要。