|
|
|
|
|
Opacity
和 rgba()
不僅是設(shè)置任何元素透明度的主要元素,也是網(wǎng)頁設(shè)計師最容易混淆的元素。我想出了一個Opacity
與 RGBA
的簡單比較指南,讓你了解差異。
什么是Opacity?
Opacity
是一個屬性,它通過 CSS 指定特定元素的透明度級別。Opacity
值的要求在 0 和 1 之間變化。
Opacity是如何工作的?
例如,要為特定元素實現(xiàn) 30% 的透明度,我們需要將Opacity
值設(shè)置為 0.3。
查看在包含文本的黑色 div
類中應(yīng)用Opacity
的示例。
.content-opacity{
background-color: rgb(0,0,0);
opacity: 0.3;
border: 10px solid #2d21ed;
}
30% Opacity
的示例輸出:
什么是 RGBA()?
rgba()
使用 red-green-blue-alpha 值定義顏色。
RGB 指定紅色、綠色和藍(lán)色的強(qiáng)度,介于 0 和 255 之間,或作為 0% 和 100% 之間的百分比值。
'A' 代表 rgba()
中的 alpha,它將不透明度定義為 0.0 到 1.0 之間的數(shù)字。這里,0.0 表示“完全透明”,1.0 表示“完全不透明”。
它是如何工作的?
例如,要為特定元素實現(xiàn) 30% 的透明度,我們需要將 alpha 值設(shè)置為 0.3。
查看 rgba()
的示例,該示例將 RGB 值指定為 0,這意味著黑色和 alpha 值為 0.3。
.content-rgba {
background-color: rgba(0,0,0,0.3);
border: 10px solid #2d21ed;
}
30% alpha 的示例輸出:
opacity 和 rgba()
盡管這兩個元素都用于元素的透明度,但rgba
和opacity
之間存在一些基本但重要的區(qū)別,這使得它們的工作方式不同。
主要區(qū)別在于,opacity
也適用于其子元素。相反, rgba()
僅將顏色的透明度應(yīng)用于該特定元素。
例如,opacity
設(shè)置為包含文本并具有邊框的 div
元素。然后,顏色元素的不透明度將應(yīng)用于邊框顏色、文本顏色以及背景顏色。另一方面,rgba()
僅影響單個聲明的透明度,如下所述。
上述輸出的示例 HTML 代碼:
<div class="main-container">
<div class="sub-container">
<div class="content-rgba">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p><p> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
</div>
<div class="content-opacity">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p><p> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
</div>
</div>
</div>
示例 CSS 代碼:
<style>
.content-rgba {
padding: 20px;
border: 5px solid #2d29ed;
letter-spacing: 1.5px;
background-color: rgba(256, 0, 0, 0.5);
}
.content-opacity {
padding: 20px;
border: 5px solid #2d29ed;
margin-top: 20px;
background-color: rgb(256, 0, 0);
opacity: 0.5;
letter-spacing: 1.5px;
}
</style>
在 opacity
屬性中,透明度應(yīng)用于父元素的每個子子元素,如邊框和文本。相比之下,rgba
只適用于 div
。
哪個更好:opacity 還是 rgba?
盡管 opacity
和 rgba
都適用于相同的透明度概念,但設(shè)計師經(jīng)常對在兩者中選擇一個感到困惑!
正如我所提到的,基本上兩者都不是一回事。因此,它始終取決于一個人對不透明度級別的要求。建議使用 rgba
,因為它提供了基于單個元素應(yīng)用不透明度的功能,但如果需要在子元素上應(yīng)用透明度,那么在這種情況下,請使用opacity
屬性。
相關(guān)文章