原本 CSS 中的顏色除了可用 16 進位來表示 RGB 顏色值之外,還可以使用預先定義好的顏色名稱。而 RGBA 是以 RGB 為基礎再加上不透明度的屬性。
檢視原始碼 CSS
1 | rgba(red, green, blue, opacity) |
其中的 red、green 及 blue 等顏色值是用 10 進位或是百分比(%)的方式來表示,允許的值為 0 到 255 之間的整數值;而 opacity 不透明度允許的值為 0 到 1 之間帶有小數的數值。
快速的看一下實際的範例:
檢視原始碼 HTML
1 2 3 4 5 6 7 8 9 | <body> <div class="rgba1">rgba(0, 0, 0, 1)</div> <div class="rgba2">rgba(100%, 100%, 0%, 0.75)</div> <div class="rgba3">rgba(144, 180, 60, 1)</div> <div class="rgba4">rgba(204, 102, 102)</div> <div class="rgba5">rgba(300, -102, 0, 1)</div> <div id="log"></div> </body> |
接著換 CSS:
檢視原始碼 CSS
1 2 3 4 5 6 7 8 9 | div { width: 220px; height: 50px; float: left; margin-right: 10px; line-height: 50px; text-align: center; border: 1px solid #000; } |
基本用法:
檢視原始碼 CSS
1 2 3 4 5 6 7 8 9 10 | .rgba1 { /* 等同於 #ffffff 或是 rgba(100%, 100%, 100%, 1) */ color: rgba(255, 255, 255, 1); /* 等同於 #000000 或是 rgba(0%, 0%, 0%, 1) */ background-color: rgba(0, 0, 0, 1); } .rgba3 { background-color: rgba(144, 180, 60, 1); } |
除了給實際的顏色值之外,也可以用百分比(%)來表示:
檢視原始碼 CSS
1 2 3 | .rgba2 { background-color: rgba(100%, 100%, 0%, 0.75); } |
若是 opacity 值沒給的話,預設會用 0;這樣表示是透明(transparent)喔:
檢視原始碼 CSS
1 2 3 4 | .rgba4 { /* 沒有指定 opacity 值時, 預設使用 0 */ background-color: rgba(204, 102, 102); } |
如果顏色值超出限定的範圍時,則會用最接近的數值:
檢視原始碼 CSS
1 2 3 4 | .rgba5 { /* 超出範圍, 所以變成最接近的 rgba(255, 0, 0, 1) */ background-color: rgba(300, -102, 0, 1); } |
只要是顏色值的部份都能使用 rgab() 來設定。但當要用程式來存取時,可能要注意一下各瀏覽器間的差異喔:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 | $(function(){ var str = ''; $('div:not(#log)').each(function(){ var $this = $(this); str += '.' + $this.attr('class') + ' : ' + $this.css('background-color') + '<br />'; }); $('#log').html(str); }); |
請問男丁
CSS3目前對於舊版瀏覽器的支援性足夠嗎?
這些規則是要瀏覽器來支援的, 目前已最新版的瀏覽器來說,基本上都是 OK。