:after和:before元素在透明边框下不可见

时间:2017-03-01 14:39:22

标签: css

我尝试动画:在anf之后:在想要位于div边界下的元素之前。下面的代码片段演示了工作案例,但如果我取消注释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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

为什么会这样?

实际上,浏览器会在background-color上绘制透明边框下方的区域。

如何修复?:

background-clip属性应用于元素时,使用background-color css属性显式告诉浏览器仅绘制元素的内容区域(不包括边框)。

.ex {
  background-clip: content-box;
  border: 2px solid transparent;
}

Read More关于background-clip

<强>演示:

&#13;
&#13;
.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);

}
&#13;
<div class="ex">hover me</div>
&#13;
&#13;
&#13;