rgb() 和 rgba() 不透明度有什么区别?

What is the difference between rgb() and rgba() opacity?

我在 SO 上发现了另一个关于 rgb 与 rgba 的问题非常相似,但它缺少关于 rgb 与不透明度 .

用法的答案

我知道两者之间的区别——rgba 只是 rgb,但带有 alpha 表示不透明度。问题是,我使用带有不透明度值的 rgb 已经有几个月甚至几年了。它一直对我有用。 rgb(255, 0, 255, 0.5)

我想知道如果两者的工作原理相同,使用一个是否有优势? rgb 存在的时间更长,所以我认为浏览器兼容性更好?一位同事还告诉我,rgba 值仅适用于背景颜色,但话又说回来,我在 codepen 中做了一些测试,它适用于 Edge 和 Chrome.

(我知道两者都是 Chrome 基于这两个都是我下载的)

相关问题:What are differences between RGB vs RGBA other than 'opacity'


这是我的代码片段

/* texts */
.one {
  color: rgba(255, 200, 0, .5);
}
.oneFive {
  color: rgb(255, 200, 0, .5);
}

/* backgrounds */
.two {
  background-color: rgb(255, 0, 255, 0.5);
}
.three {
  background-color: rgba(0, 0, 255, 0.5);
}



/*          */
/* settings */
/*          */
.two, .three {
  height: 50px;
}
.two {
  margin-top: 30px;
}
.two, .three, .zero {
  color: white;
}
.one, .oneFive {
  height: 50px;
  font-weight: bold;
  font-size: 2em;
  padding-left: 40px;
  padding-top: 20px;
}
body { 
  background-color: #444; 
  color: white; 
}
.zero {
  background-color: darkgreen;
  width: 300px;
  height: 350px;
  position: absolute;
  top: 35px;
  z-index: -1;
}
dark grey 100% opacity

<div class="zero">dark green 100% opacity</div>

<div class="oneFive">rgb yellow text 70% opacity</div>
<div class="one">rgba yellow text 70% opacity</div>

<div class="two">rgb 50% background opacity</div>
<div class="three">rgba 50% background opacity</div>

Makes me wonder if there's an advantage to use one if both works the same?

这与优势无关,但这是 the Specification

中新定义的东西

rgb() and rgba(), and hsl() and hsla() are now aliases of each other (all of them have an optional alpha). ref

Also for legacy reasons, an rgba() function also exists, with an identical grammar and behavior to rgb(). ref

所以 rgba() 应该消失,只应该使用 rgb() 但这不会发生,因为它会产生很多问题和冲突,所以 rgba() 仍然会考虑并且将仅具有与 rgb()

相同的语法

另请注意,新语法不再包含逗号:

rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) |
  rgb( <number>{3} [ / <alpha-value> ]? )
<alpha-value> = <number> | <percentage>

例如,您应该写 rgb(255 65 40)rgb(255 65 40 / 80%),但由于遗留原因,仍然支持逗号语法:

For legacy reasons, rgb() also supports an alternate syntax that separates all of its arguments with commas:

按要求回答:

我要大胆地说这是浏览器翻译了 rgb 中设置的具有不透明度值的本质上“不正确”的值。

如果您查看计算选项卡下的浏览器开发工具,您会注意到 rgb 值计算为 rgba(至少在 Firefox 中)。

我认为任何支持 CSS3 的浏览器都会“修复”属性。

另外 同事告诉我 rgba 值只适用于背景色:你的同事错了。

rgb 存在的时间更长,所以我认为浏览器兼容性更好? 我不会这么说。您永远不会注意到性能受到影响,但如果浏览器不必“修复”传递给 rgb 集的不正确值,您就会减少浏览器的工作量。 更新: rgbargb 的别名,所以它实际上不是 修复 任何东西,它只是传递给 rgb 无论如何。

这里有一些关于 rgbrgba 的文档——特别是函数的别名:

https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb_colors