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

时间:2018-03-16 19:15:23

标签: html css html5 css3 pseudo-element

我试图过渡到一些' 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>
&#13;
&#13;
&#13;

我进行过渡以将a ::的宽度从0改为100% 但是宽度100%是以.test的大小呈现的,而不是&#39; a&#39;的大小。所以下划线的长度不适合文本。它适合屏幕尺寸。

我无法理解为什么a :: after并不遵循其父级的大小,a。并想知道如何制作一个:: after来跟随&#39; a&#39;。

的大小。

2 个答案:

答案 0 :(得分:3)

您可以添加:

.test {
  display: inline-block;
}

.test a {
  display: inline-block;
}

这样盒子的大小就与内容相匹配。

&#13;
&#13;
.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%;
}
&#13;
<div class="test">
  <a href="#">text for the test</a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这是另一个没有使用伪元素且没有大小问题的想法:

.test a {
  font-size: 5vw;
  text-decoration: none;
  color: #000;
  padding-bottom:0.1em;
  background-image:linear-gradient(#000,#000);
  background-size:0% 0.1em;
  background-position:0 100%;
  background-repeat:no-repeat;
  transition: 0.5s ease-in-out;
}

.test a:hover {
  background-size:100% 0.1em;
}
<div class="test">
  <a href="#">text for the test</a>
</div>