我正在尝试动画:anf:在打算放在Div Border下的元素之前。下面的摘要证明了工作案例,但是如果我不注重border: 2px solid transparent;
,伪元素就会变得不可见。我试图更改盒子尺寸 - 无论如何。
问题是:为什么透明边框表现为不透明?
.ex {
position: relative;
box-sizing: border-box;
width: 100px;
height: 40px;
line-height: 2em;
text-align: center;
background-color: lightgreen;
/* border: 2px solid transparent; */
margin: 30px;
}
.ex::after, .ex::before {
content: " ";
z-index: -1;
display: block;
position: absolute;
width: 0;
height: 0;
background: red;
transition: all .2s ease;
}
.ex::before {
top: -2px;
left: -2px;
}
.ex::after {
bottom: -2px;
right: -2px;
}
.ex:hover::after, .ex:hover::before {
width: calc(100% + 4px);
height: calc(100% + 4px);
}
<div class="ex">hover me</div>
为什么会发生?
实际上,透明边框下方的区域由浏览器用background-color
绘制。
如何修复?:
使用 background-clip
css属性明确告诉浏览器,仅将background-color
属性应用于元素时仅绘制元素的内容区域(不包括边框)。
.ex {
background-clip: content-box;
border: 2px solid transparent;
}
阅读有关background-clip
的更多信息:
演示:
.ex {
position: relative;
box-sizing: border-box;
width: 100px;
height: 40px;
line-height: 2em;
text-align: center;
background-color: lightgreen;
border: 2px solid transparent;
background-clip: content-box;
margin: 30px;
}
.ex::after, .ex::before {
content: " ";
z-index: -1;
display: block;
position: absolute;
width: 0;
height: 0;
background: red;
transition: all .2s ease;
}
.ex::before {
top: -2px;
left: -2px;
}
.ex::after {
bottom: -2px;
right: -2px;
}
.ex:hover::after, .ex:hover::before {
width: calc(100% + 4px);
height: calc(100% + 4px);
}
<div class="ex">hover me</div>