为什么这两个元素不同时过渡?

Why do these 2 elements not transition at the same time?

我有一个包含 2 个伪元素(.card-title::before.card-title::after)的元素,其过渡将宽度从 0px 更改为 40px。

原来的过渡速度是0.5s,为了演示我改成了15s,这样大家可以清楚的看到::before伪元素先于::after.[=17开始=]

如果看不到,请尝试在整页中打开代码段。

为什么会这样,我该如何解决?

我可以通过向 ::before 添加一个非常短的延迟(比如 0.05 秒)来解决这个问题,但我想你能理解为什么我不喜欢这个想法。

*,
*::before,
*::after {
 box-sizing: border-box;
}

body {
 display: grid;
 place-items: center;
 height: 100vh;
 background: #eee;
}

.card {
 height: 100px;
 width: 100px;
}

.card-body {
 color: white;
 height: 100%;
 background: #777;
}

.card-title {
 position: relative;
 background: yellow;
 height: 45px;
}

.card-title::before {
 content: '';
 position: absolute;
 background: red;
 width: 0;
 top: 0;
 bottom: 0;
 right: 100%;
 z-index: -1;
 transition: width 15s linear;
}

.card-title::after {
 content: '';
 position: absolute;
 background: red;
 width: 0;
 top: 0;
 bottom: 0;
 left: 100%;
 z-index: -1;
 transition: width 15s linear;
}

/* Hover effect */
.card-body:hover .card-title::before,
.card-body:hover .card-title::after {
 width: 40px;
}
<div class="card">
 <div class="card-body">
  <h3 class="card-title"></h3>
 </div>
</div>

我不确定,但您的问题可能是由舍入问题引起的,一次过渡向下舍入一个像素,一次向上舍入。

但是,您可以从使用更改宽度切换到使用 transform: scaleX(1); 调整比例,这无论如何都更高效。以下内容适用于 Chrome 和 Firefox。

*,
*::before,
*::after {
 box-sizing: border-box;
}

body {
 display: grid;
 place-items: center;
 height: 100vh;
 background: #eee;
}

.card {
 height: 100px;
 width: 100px;
}

.card-body {
 color: white;
 height: 100%;
 background: #777;
}

.card-title {
 position: relative;
 background: yellow;
 height: 45px;
}

.card-title::before {
 content: '';
 position: absolute;
 background: red;
 width: 40px;
 top: 0;
 bottom: 0;
 right: 100%;
 z-index: -1;
 transition: transform 15s linear;
 transform: scaleX(0);
 transform-origin: right;
}

.card-title::after {
 content: '';
 position: absolute;
 background: red;
 width: 40px;
 top: 0;
 bottom: 0;
 left: 100%;
 z-index: -1;
 transition: transform 15s linear;
 transform: scaleX(0);
 transform-origin: left;
}

/* Hover effect */
.card-body:hover .card-title::before,
.card-body:hover .card-title::after {
 transform: scaleX(1);
}
<div class="card">
 <div class="card-body">
  <h3 class="card-title"></h3>
 </div>
</div>