【发布时间】:2020-12-07 07:50:54
【问题描述】:
【问题讨论】:
标签: html css background position
【问题讨论】:
标签: html css background position
这是一个使用遮罩的想法,其中技巧是考虑与遮罩层相同的图像,并且将按照图像形状切割覆盖层
.box {
background:#fff;
position:relative;
width:200px;
display:inline-block;
-webkit-mask:url(https://i.ibb.co/2ngRVZQ/Daco-2761771.png) center/contain no-repeat;
}
img {
display:block;
max-width:100%;
}
.box:before {
content:"";
position:absolute;
left:0;
right:0;
top:0;
height:50%; /* adjust this */
background:rgba(255,0,0,0.5);
}
body {
background:#f2f2f2;
}
<div class="box">
<img src="https://i.ibb.co/2ngRVZQ/Daco-2761771.png">
</div>
<div class="box" style="width:100px;">
<img src="https://i.ibb.co/2ngRVZQ/Daco-2761771.png">
</div>
你也可以像下面这样优化:
.box {
--img: url(https://i.ibb.co/2ngRVZQ/Daco-2761771.png);
background: #fff;
position: relative;
width: 200px;
display: inline-block;
background: var(--img) center/contain no-repeat;
-webkit-mask: var(--img) center/contain no-repeat;
}
img {
display: block;
max-width: 100%;
}
.box:before {
content: "";
position: absolute;
left: 0;
right: 0;
top: 0;
height: var(--h,50%); /* adjust this */
background: var(--c, rgba(255, 0, 0, 0.5));
}
.box:after {
content: "";
display: block;
padding-top: 150%; /*maintain the same ratio (adjust based on your real image) */
}
body {
background: #f2f2f2;
}
<div class="box"></div>
<div class="box" style="width:100px;--c:rgba(0,255,0,0.5);--img:url(https://i.ibb.co/3NVCq38/Daco-1325460.png);--h:70%"></div>
【讨论】: