边界转换中不需要 Space

Unwanted Space in Border Transition

我在 CSS 中为 div 做了一个边框转换,基本上边框以时钟工作方式可见。

Here it is

将鼠标悬停在灰色矩形上可以看到它。

下面的代码因为网站要求我提供,请查看link

<div class="outerBox"></div>

但是,正如你在笔中看到的那样,在灰色矩形的边缘和边界,两端没有正确相遇。

关于为什么这会发生的任何想法?

更新

实际上,找到了解决方案。

我发现问题与 边框的宽度改变 div 元素的框大小 的方式有关。

基本上,使边框为 2px 是在 div 元素上增加 2px 的宽度(我相信在每一边),从而导致 space 和未满足的结束。

解决方案 是添加声明

box-sizing: border-box;

到 ::before 和 ::after 伪元素(为了安全起见,我将它添加到 div 元素)然后 width div元素不再受边框宽度的影响。

如果您单击我问题中的 link,您会看到边框现在很好地包围了矩形。

要看之前的状态,把box-sizing: border-box注释掉即可;声明实例。

一个更简单的多背景解决方案:

* {
  box-sizing: border-box;
}

body {
  background: silver;
}

.box {
  background-color: white;
  height: 10em;
  margin: 2em auto;
  width: 10em;
}
.box:hover {
  animation: border 1s linear forwards;
  background-image: linear-gradient(to left, red, red), linear-gradient(to left, red, red), linear-gradient(to left, red, red), linear-gradient(to left, red, red);
  background-position: top left, top right, bottom right, bottom left;
  background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;
}

@keyframes border {
  0% {
    background-size: 0% 4px, 4px 0%, 0% 4px, 4px 0%;
  }
  25% {
    background-size: 100% 4px, 4px 0%, 0% 4px, 4px 0%;
  }
  50% {
    background-size: 100% 4px, 4px 100%, 0% 4px, 4px 0%;
  }
  75% {
    background-size: 100% 4px, 4px 100%, 100% 4px, 4px 0%;
  }
  100% {
    background-size: 100% 4px, 4px 100%, 100% 4px, 4px 100%;
  }
}
<div class="box"></div>