使用场景: 在做两个元素的连接处的UI适配时,图片的颜色不能保证一定跟背景颜色或者是主色调保持一致时,会显得比较突兀。
注意:本次使用的方法只适用于背景色为纯色
正常情况下:
使用图片渐变后:
- 利用 background-image: linear-gradient(direction,color1,color2), url(*) (推荐)
<head> <style> .linearBg{ background-image: linear-gradient(90deg,transparent,#fff), url(1.jpg); // #fff表示需要兼容的底色 width: 200px; height: 200px; background-size: 40%, contain; // 40%表达需要渐变的宽度 background-repeat: no-repeat; background-position: right; // right表示渐变对齐的方向 } </style> </head> <body> <div class="linearBg"></div> </body>
复制
- 利用css伪类添加渐变透明蒙层
<head> <style> .linearBg{ background-image:url(1.jpg); width:200px; height:200px; background-size: contain; background-repeat: no-repeat; background-position: center; position: relative; &::before{ content: ''; position: absolute; top: 50%; right: 0%; width: 40%; // 40%表达需要渐变的宽度 height: 100%; transform: translateY(-50%); background: linear-gradient(90deg,transparent,#fff); // #fff表示需要兼容的底色 } } </style> </head> <body> <div class="linearBg"></div> </body>
复制