纯CSS根据图片取色设置背景色

2022年11月21日

650781310.jpeg

前几天无意间访问到了个韩国的动漫视频站,然后看到个页面每个div背景色都不同疑似根据图片进行的取色,然后就想看看他是用什么js设置的,f12一看发现好像不是js,然后我就以为是写死的,想看看怎么写的,结果一看不要紧,学到个骚操作。

代码

Html部分的核心代码

<div class="board">
<div class="images">
<div class="image" style="background-image:url(图1)"></div>
<div class="image" style="background-image:url(图2)"></div>
<div class="image" style="background-image:url(图3)"></div>
</div>
<div class="blurred" style="background-image:url(图1)"></div>
</div>

Css部分核心代码

 .board {
background: rgb(208, 208, 208);
height: 208px;
position: relative;
overflow: hidden;
display: flex;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
}
.board .blurred {
position: absolute;
inset: 0px;
background-size: 20000%;
background-position: center top;
background-repeat: no-repeat;
filter: brightness(0.9);
}

分析

从代码里可以看到,实际上他就是用<div class="blurred" style="background-image:url(图1)"></div>来把图1设置成了背景,然后使用background-position: center top;让背景图x轴居中y轴靠上,然后再使用background-size: 20000%;将背景图放大200倍,然后图片背景看起来就是纯颜色的了。

根据需求我们可以更改background-position的值,设置取色位置!

本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!

评论区

暂无评论,快来抢沙发