CSS3實現(xiàn)背景透明文字不透明的示例代碼

最近遇到一個需求,要在圖片上顯示帶有半透明背景的文字,效果如下圖所示:
需求.png
看到這個需求之后,第一反應(yīng)是使用CSS3中的opacity設(shè)置元素的透明度。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>背景透明,文字也透明</title> <style> * { padding: 0; margin: 0; } .container { width: 600px; height: 400px; background: url('https://img1.dongqiudi.com/fastdfs3/M00/18/56/ChOxM1stHByARuNmAAGsJDKXtuM269.jpg') no-repeat; background-size: cover; -webkit-background-size: cover; -o-background-size: cover; background-position: center 0; } .demo { position: absolute; width: 260px; height: 60px; top: 260px; line-height: 60px; text-align: center; background-color: black; opacity: 0.5; } .demo p { color: #FFF; font-size: 18px; font-weight: 600; } </style> </head> <body> <div class="container"> <div class="demo"> <p>2018世界杯已開幕:10天</p> </div> </div> </body> </html>
效果如下:
背景透明,文字也透明.png
這樣貌似也滿足了需求,不過并不完美,設(shè)置opacity之后,整個元素都半透明了,造成文字顯得模糊,這樣的解決方式并不可取。
其實實現(xiàn)透明的CSS方法并不只有設(shè)置opacity一種方式。還有另外兩種:
- css3的rgba(red, green, blue, alpha),alpha的取值從 0 到 1,如rgba(255,255,255,0.8)
- IE專屬濾鏡 filter:Alpha(opacity=x),x 的取值從 0 到 100,如filter:Alpha(opacity=80)
在這里我采用了設(shè)置rgba的方式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>背景透明,文字不透明</title> <style> * { padding: 0; margin: 0; } .container { width: 600px; height: 400px; background: url('https://img1.dongqiudi.com/fastdfs3/M00/18/56/ChOxM1stHByARuNmAAGsJDKXtuM269.jpg') no-repeat; background-size: cover; -webkit-background-size: cover; -o-background-size: cover; background-position: center 0; } .demo { position: absolute; width: 260px; height: 60px; top: 260px; line-height: 60px; text-align: center; background-color: rgba(0,0,0,0.5); } .demo p { color: #FFF; font-size: 18px; font-weight: 600; } </style> </head> <body> <div class="container"> <div class="demo"> <p>2018世界杯已開幕:10天</p> </div> </div> </body> </html>
效果如下:
背景透明,文字不透明.png
這樣設(shè)置之后,文字顯得清晰了許多。
小結(jié)
其實要實現(xiàn)這個需求,并不只有這一種思路,還可以用兩個DIV放在同一個位置,一個是半透明的背景DIV,一個是文字DIV,一樣可以解決問題,但是需要寫絕對定位或負(fù)margin,并出現(xiàn)空內(nèi)容的DIV,這種方法在有些場景下會顯得略微復(fù)雜,如下示例所示,所以在實際需求場景中還是要具體問題具體分析。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用css3背景漸變中的透明度來設(shè)置不同顏色的背景漸變
根據(jù)用戶輸入的顏色來配置整個主題的顏色,發(fā)現(xiàn)css3的背景漸變中的透明度可以解決這個問題,具體的實現(xiàn)如下,大家可以參考下2014-03-31css3背景圖片透明疊加屬性cross-fade簡介及用法實例
據(jù)說iOS6系統(tǒng)(iPhone5)增加了兩個CSS3屬性,一個是CSS3 filters – CSS3濾鏡另外一個是CSS3 Cross-fade – CSS3交叉淡入淡出,接下來為您介紹cross-fade屬性,感興趣的朋友2013-01-08