我正在尝试使用伪元素之前和之后的背景效果,使其比实际元素高和宽一个像素,但似乎总是在右边或左边多了一个像素。这仅在浏览器最大化(Firefox,Chrome和Edge)时发生,而在浏览器宽度较小时则不会发生。
*, *::before, *::after{ box-sizing: border-box; }
body {
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
background-color: #111;
}
img {
max-width: 300px;
display: block;
padding: 4px;
}
.main-box {
position: relative;
}
.img-box {
padding: 0;
margin: 0;
background-color: #000;
}
.img-box::before{
content: '';
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
filter: blur(10px);
z-index: -2;
}
.img-box::after{
content: '';
position: absolute;
top: -1px;
left: -1px;
right: -1px;
bottom: -1px;
z-index: -1;
}
.img-box::before, .img-box::after{
background-image: linear-gradient(45deg, #ff0000, #111, #0000ff);
opacity: 0.7;
transition: opacity ease-out 150ms;
}
.main-box:hover .img-box::after {
opacity: 1;
}
<div class="main-box">
<div class="img-box"><img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" alt="keyboard"></div>
</div>
图片上的图片不太清楚,但是在浏览器中,背景图片的所有侧面都增加了1px,左侧是2px。
答案 0 :(得分:0)
这看起来像是抗锯齿。我想您已将浏览器的操作系统缩放级别设置为100%以外的值。
某些浏览器将尝试舍入定位,但是在某些缩放级别上,此操作无法正确完成,您最终将一侧放到另一侧并盖上。
要避免这种情况,可以使用translate
属性,该属性应允许适当的抗锯齿功能(它会模糊,但大小相同)。
*, *::before, *::after{ box-sizing: border-box; }
body {
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
background-color: #111;
}
img {
max-width: 300px;
display: block;
padding: 4px;
}
.main-box {
position: relative;
}
.img-box {
padding: 0;
margin: 0;
background-color: #000;
}
.img-box::before{
content: '';
position: absolute;
top: 0px;
left: 0px;
width: calc( 100% + 2px );
height: calc( 100% + 2px );
transform: translate(-1px,-1px);
filter: blur(10px);
z-index: -2;
}
.img-box::after{
content: '';
position: absolute;
top: 0px;
left: 0px;
width: calc( 100% + 2px );
height: calc( 100% + 2px );
transform: translate(-1px,-1px);
z-index: -1;
}
.img-box::before, .img-box::after{
background-image: linear-gradient(45deg, #ff0000, #111, #0000ff);
opacity: 0.7;
transition: opacity ease-out 150ms;
}
.main-box:hover .img-box::after {
opacity: 1;
}
<div class="main-box">
<div class="img-box"><img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png" alt="keyboard"></div>
</div>