我想要一个覆盖图像的div。我可以通过在父元素中使用position: relative,并在div中使用position: absolute来使div覆盖图像,但是background-color会填充父元素的padding,导致它们不能正确地覆盖。
下面是一个演示问题的片段。
.parent {
position: relative;
padding: 10px;
width: 40%;
}
.image {
width: 100%;
height: 100%;
border-radius: 13px;
}
.overlay {
position: absolute;
background-color: red;
width: 100%;
height: 100%;
border-radius: 13px;
left: 0;
top: 0;
opacity: 0.2;
}
我可以通过一些calc()来减去padding来实现相当接近的效果。这几乎可以工作,但是div在底部填充得有点多。无论如何,我不想为padding硬编码很多值,所以即使它完全工作,我也不太喜欢这个解决方案。
下面是一个展示calc()方法的片段。
.parent {
position: relative;
padding: 10px;
width: 40%;
}
.image {
width: 100%;
height: 100%;
border-radius: 13px;
}
.overlay {
position: absolute;
background-color: red;
width: calc(100% - 2 * 10px);
height: calc(100% - 2 * 10px);
border-radius: 13px;
left: 10px;
top: 10px;
opacity: 0.2;
}
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号