html - 将伪 a::after 的宽度作为容器

标签 html css pseudo-element

我正在尝试过渡到一些“a”标签。也就是当鼠标悬停时,下划线在其文本字符串上从左向右慢慢增长。

我想我应该用 a 标签的伪造它,我成功地做了一个类似的转换,但它有一个问题让我卡住了。

.test a {
  font-size: 5vw;
  text-decoration: none;
  color: #000;
}

.test a::after {
  content: '';
  display: block;
  height: 0.1em;
  left: 0;
  background-color: #000;
  transition: 0.5s ease-in-out;
  width: 0;
}

.test a:hover::after {
  width: 100%;
}
<div class="test">
  <a href="#">text for the test</a>
</div>

我将 a::after 的宽度从 0 更改为 100% 但宽度 100% 是由 .test 的大小呈现的,而不是 'a' 的大小。所以下划线的长度不适合文本。它适合屏幕尺寸。

我无法理解为什么 a::after 不遵循其父级 a 的大小。并且想知道如何使 a::after 遵循 'a' 的大小。

最佳答案

您可以添加:

.test {
  display: inline-block;
}

.test a {
  display: inline-block;
}

使框的大小与内容匹配。

.test {
  display: inline-block;
}

.test a {
  font-size: 5vw;
  text-decoration: none;
  color: #000;
}

.test a::after {
  content: '';
  display: block;
  height: 0.1em;
  left: 0;
  background-color: #000;
  transition: 0.5s ease-in-out;
  width: 0;
}

.test a:hover::after {
  width: 100%;
}
<div class="test">
  <a href="#">text for the test</a>
</div>

关于html - 将伪 a::after 的宽度作为容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328010/

相关文章:

javascript - 在循环中创建多个 Canvas ,仅调用最后一个函数

html - 文本字段左对齐,数字应右对齐

html - 仅在 IE9 上出现下拉菜单问题

html css 我怎样才能缩短标签

html - 导航显示顺序错误

HTML CSS,::添加后不考虑父级的溢出:隐藏

CSS - 为图像 mask 使用伪元素

javascript - 使一个 div 的大小等于另一个

javascript - 删除焦点上的 SweetAlert 按钮轮廓

html - 你可以使用 2 :before pseudo classes in the same div?