平常我们要实现倒影的效果,一般的做法是使用多个DOM元素绝对定位+scale(负-1) 或者 rotate。这种方法的缺点是占据空间以及DOM元素过多。
在使用 webkit 内核的浏览器中(ch rom e,safari,移动端浏览器),可以使用-webk IT -box-reflect属性来实现倒影,语法如下所示
[ above | below | right | left ]? <length>? <image>?
该值包涵了三部分:方位+偏移量+遮罩层
方位是必不可少的;在使用遮罩层的时候,偏移量是不可少的,如没有则用零代替
!!! 重要 :遮罩层的效果与颜色无关,例如使用渐变颜色做遮罩,都是实色则透明,透明则暴漏原始颜色
使用示例如下所示:
<!DOCTY PE ht ML > <html> <head> < ;m eta charset="utf-8"> <meta n am e="viewport" content="width=device-width"> <title>JS Bin</title> <style type="text/csss"> .box{ width:200px; h ei ght:200px; m arg in-bottom:20px;transform:scale(-1,1); background -i mage:linear-gra die nt(90 deg , red ,yellow);-webkit-box-reflect:below 10px linear-gradient(180deg,transparent, # 000); } </style> </head> <body> <div class="box"></div> </body> </html>
效果如下:
如果需要在firefox中实现类似效果,可以使用-moz-element()函数来实现,但是在旋转下效果差别 较大 ,如下所示。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <style type="text/css"> .box{ width:200px; height:200px; mar gin :100px 0 0 100px; } .box1{ background-image:linear-gradient(180deg,red,yellow); transform:scale(1,-1) rotate(45deg)} .box2{ background-image:-moz-element(#box1); } </style> </head> <body> <div class="box box1" id="box1"></div> <div class="box box2" id="box2"></div> </body> </html>
在c hr ome下使用-webkit-box-reflect的效果是这样的
如果要兼容IE浏览器还可以使用SVG或者canvas来做,SVG主要 利用 pattern+mask+linearGradient+scale来做,canvas使用scale+globalComposite opera tion。
SVG例子部分代码如下:
<svg width="200" height="200"> <defs> <linearGradient id="a" x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" style="stop-color:yellow"/> <stop offset="100%" style="stop-color:red"/> </linearGradient> <linearGradient id="b" x1="0" y1="0" x2="0" y2="100%"> <stop offset="0%" style="stop-color:rgba(255,255,255,0)"/> <stop offset="100%" style="stop-color:rgba(255,255,255,1)"/> </linearGradient> <mask id="c" x="0" y="0" width="1" height="1"> <rect x="0" y="0" width="100%" height="100%" style="fill:url(#b)" /> </mask> </defs> <rect x="0" y="0" width="200" height="200" style="fill:url(#a);" mask="url(#c)"> </svg>
canvas例子部分代码如下
VAR canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); var linearGradient1 = ctx.createLinearGradient(0,0,0,200); linearGradient1.addColorStop(0,"red"); linearGradient1.addColorStop(1,"yellow"); var linearGradient2 = ctx.createLinearGradient(0,0,0,200); linearGradient2.addColorStop(0,"transparent"); linearGradient2.addColorStop(1,"#ffffff"); ctx.fillStyle = linearGradient1; ctx.fillRect(0,0,200,200); ctx.globalCompositeOperation = 'destination-out'; ctx.fillStyle = linearGradient2; ctx.fillRect(0,0,200,200);
以上便是倒影实现的各种方法,对比之下用css3的-webkit-box-reflect实现最 简单 效果也好。希望对大家的学习有所帮助,也希望大家多多支持。
总结
以上是 为你收集整理的 CSS3 Notes: -webkit-box-reflect实现倒影的实例 全部内容,希望文章能够帮你解决 CSS3 Notes: -webkit-box-reflect实现倒影的实例 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于CSS3 Notes: -webkit-box-reflect实现倒影的实例的详细内容...