CSS 中的 rgb() 函数用于使用 RGB(红、绿、蓝)颜色模型定义颜色值。它允许您通过指定这三种原色中每一种的强度来指定颜色。
要添加颜色透明度,可以将可选的 <alpha-value> 传递给 rgb() 函数。
旧函数 rgba() 是函数 rgb() 的别名,它们都接受相同的参数并以相同的方式运行。
可能的值
rgb() 函数的函数表示法是 rgb(R G B[ / A])。
- R、G、B:可以包含任何格式,分别代表红色、绿色和绿色通道:
- <number>:0 到 255 之间的任何数字。
- <percentage>:介于 0% 和 100% 之间的任何值。
- 关键词 none
- A:表示颜色的透明度。它是一个可选值。
- <alpha-value>:0 到 1 之间的任何数字,其中 1 对应于完全不透明度,0 对应于完全透明。
- 关键词 none
红色、绿色和蓝色分量的值在序列化中四舍五入,因为函数表示法将其序列化为 sRGB。
语法
rgb(255 255 255) | rgb(255, 255, 255) | rgb(255 255 255 /0.5)
CSS rgb() - 数字值
以下示例显示了 rgb() 函数的用法,其中所有三个值都带有和不带有 alpha 值(数字值):
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
border: 2px solid black;
margin-bottom: 10px;
}
.color-rgb-red{
background-color: rgb(255 0 0);
}
.color-rgb-green{
background-color: rgb(0 255 0);
}
.color-rgb-blue{
background-color: rgb(0 0 255);
}
.color-rgb-alpha{
background-color: rgba(255 0 0 /0.5);
}
</style>
</head>
<body>
<div class="color-rgb-red">rgb(255 0 0)</div>
<div class="color-rgb-green">rgb(0 255 0)</div>
<div class="color-rgb-blue">rgb(0 0 255)</div>
<div class="color-rgb-alpha">rgba(255 0 0 /0.5)</div>
</body>
</html>
CSS rgb() - 百分比值
以下示例显示了 rgb() 函数的用法,其中所有三个值都带有和不带有 alpha 值(百分比值):
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
border: 2px solid black;
margin-bottom: 10px;
}
.color-rgb-red {
background-color: rgb(70% 30% 10%);
}
.color-rgb-comma {
background-color: rgb(0%, 55%, 20%);
}
.color-rgb-blue {
background-color: rgb(10% 10% 85%);
}
.color-rgb-alpha-number {
background-color: rgba(0% 40% 50% /0.5);
}
.color-rgb-alpha-percent {
background-color: rgba(70% 0% 50% /12%);
}
</style>
</head>
<body>
<div class="color-rgb-red">rgb(70% 30% 10%)</div>
<div class="color-rgb-comma">rgb(comma-separated)</div>
<div class="color-rgb-blue">rgb(10% 10% 85%)</div>
<div class="color-rgb-alpha-number">rgba(0% 40% 50% /0.5)</div>
<div class="color-rgb-alpha-percent">rgba(70% 40% 50% /12%)</div>
</body>
</html>