我希望使用background-size contains在比例大小的图像上显示叠加颜色。我的占位符div正确扩展到高度,但不是宽度:
.prop {
background-image: url('http://via.placeholder.com/1600x1200');
width:100vw;
background-size: contain;
height: 100vh;
background-position: center;
background-repeat: no-repeat;
border: inset 70px transparent;
box-sizing: border-box;
}
.placeholder {
background:red;
height:100%;
opacity:0.5;
}

<div>
<div class="prop">
<div class="placeholder"></div>
</div>
</div>
&#13;
答案 0 :(得分:1)
由于您提到图像的宽高比始终为4:3(例如1600×1200),因此有一个相当直接的解决方案:您只需要给.placeholder
一个背景图像具有相同的宽高比,并且相对于其父.prop
绝对定位,你很高兴。
使用以下其他样式更新代码:
.prop {
position: relative;
}
.placeholder {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 3"><rect style="fill: red; fill-opacity: 0.5;" width="4" height="3" x="0" y="0"></rect></svg>');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
}
说明:这里我使用了4px x 3px SVG,<rect>
元素设置为red
,并将填充的不透明度降低到0.5
:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 3">
<rect style="fill: red; fill-opacity: 0.5;" width="4" height="3" x="0" y="0"></rect>
</svg>
你可以use this SVG markup as part of the data URI for the background-image
property。请参阅概念验证示例:
.prop {
background-image: url('http://via.placeholder.com/1600x1200');
width: 100vw;
background-size: contain;
height: 100vh;
background-position: center;
background-repeat: no-repeat;
border: inset 70px transparent;
box-sizing: border-box;
position: relative;
}
.placeholder {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 3"><rect style="fill: red; fill-opacity: 0.5;" width="4" height="3" x="0" y="0"></rect></svg>');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
}
<div>
<div class="prop">
<div class="placeholder"></div>
</div>
</div>
答案 1 :(得分:0)
您应该将background-size:contain
改为background-size:100% 100%
,如此
.prop {
background-image: url('http://via.placeholder.com/1600x1200');
background-size:100% 100%;
background-position: center;
background-repeat: no-repeat;
border: inset 70px transparent;
box-sizing: border-box;
}
.placeholder {
background:red;
height:100vh;
opacity:0.5;
width:100%;
}
<div>
<div class="prop">
<div class="placeholder"></div>
</div>
</div>