CSS3实现背景透明文字不透明的示例代码

Oriel ·
更新时间:2024-09-21
· 768 次阅读

最近遇到一个需求,要在图片上显示带有半透明背景的文字,效果如下图所示:

需求.png

看到这个需求之后,第一反应是使用CSS3中的opacity设置元素的透明度。

<!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

这样貌似也满足了需求,不过并不完美,设置opacity之后,整个元素都半透明了,造成文字显得模糊,这样的解决方式并不可取。

其实实现透明的CSS方法并不只有设置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)

在这里我采用了设置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

这样设置之后,文字显得清晰了许多。

小结

其实要实现这个需求,并不只有这一种思路,还可以用两个DIV放在同一个位置,一个是半透明的背景DIV,一个是文字DIV,一样可以解决问题,但是需要写绝对定位或负margin,并出现空内容的DIV,这种方法在有些场景下会显得略微复杂,如下示例所示,所以在实际需求场景中还是要具体问题具体分析。



示例 CSS CSS3

需要 登录 后方可回复, 如果你还没有账号请 注册新账号