CSS3实现背景透明文字不透明的示例代码
前端  /  管理员 发布于 7年前   167
最近遇到一个需求,要在图片上显示带有半透明背景的文字,效果如下图所示:
需求.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一种方式。还有另外两种:
在这里我采用了设置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,这种方法在有些场景下会显得略微复杂,如下示例所示,所以在实际需求场景中还是要具体问题具体分析。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号