实现动画边框底部的正确方法是什么?

What's the correct way of implementing animated border bottom?

是否应该单独div?我不知道如何将它应用到已经有一些内容的 div。

.dashed-line {
  height: 3px;
  width: 700px;
  background: linear-gradient(90deg, red 50%, transparent 50%), linear-gradient(90deg, red 50%, transparent 50%);
  background-size: 0px 0px, 15px 4px, 4px 0px, 4px 0px;
  background-position: 0px 0px, 200px 100px, 0px 100px, 200px 0px;
  margin-left: 15px;
  animation: border-dance 7s infinite linear;

}
@keyframes border-dance {
  0% {
    background-position: 300px 0px, 0px 116px, 0px 0px, 216px 150px;
  }
  100% {
    background-position: 0px 0px, 300px 116px, 0px 150px, 216px 0px;
  }
}
<div class="dashed-line"></div>

这种情况 pseudo-elements ::before::after 特别适合。

基本上,它们允许您向页面添加并非实际“内容”的元素。也可以通过contentcss属性进行一些文字修饰。或者您可以将 属性 保留为空字符串 '' 并利用您已将“pseudo-div” 添加到节点的事实。

span {
  position: relative;
}
span::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  width: 100%;
  background: linear-gradient(90deg, red 50%, transparent 50%), linear-gradient(90deg, red 50%, transparent 50%);
  background-size: 0px 0px, 15px 4px, 4px 0px, 4px 0px;
  background-position: 0px 0px, 200px 100px, 0px 100px, 200px 0px;
  animation: border-dance 7s infinite linear;

}
@keyframes border-dance {
  0% {
    background-position: 300px 0px, 0px 116px, 0px 0px, 216px 150px;
  }
  100% {
    background-position: 0px 0px, 300px 116px, 0px 150px, 216px 0px;
  }
}
<span> hello i have some content </span>

您可以使用更简单的语法来执行此操作:

.box {
  --p:10px; /* width of the pattern */
  --w:4px;  /* width of the gap inside the pattern */
  --h:3px;  /* height of line */

  padding: 8px;
  font-size:20px;
  display: inline-block;
  background: 
    linear-gradient(90deg, red calc(100% - var(--w)), transparent 0)
    0 100% / var(--p) var(--h) repeat-x;
  animation: move 0.3s linear infinite;
}

@keyframes move {
  to {
    background-position: var(--p) 100%;
  }
}
<div class="box">
  some text
</div>