st88 st88 - 4 months ago 10
HTML Question

CSS-Transition doesn't work on pseudo-element

The idea is that some kind of underscore appears when the hyperlink appears. The underscore shall grow slowly to it's full size.

That's what I got so far:



.wrap {
margin: 10px auto;
width: 600px;
}

#test {
text-decoration: none;
}

#test:after {
width: 0;
transition: all 3s;
}

#test:hover:after {
content: '';
display: block;
width: 100%;
border: 3px solid teal;
}

<div class="wrap">
<a id="test" href="#">Some dummy-text for testing ...</a>
</div>





The underscore appears and disappears as expected. But without transition.

I have seen other websites which uses such effects on these browser (IE 11) here. So it should generally work.

What I'm doing wrong?

Specifying the transition on element-without-hover is how it shall be done. As far as I know ...

Answer

It's because you aren't adding the content until the :hover state.

You should define as much as possible in the initial state and only change the required properties for the :hover state.

Try

#test:after {
  content: "";
  display: block;
  width: 0;
  transition: all 3s;
}

.wrap {
  margin: 10px auto;
  width: 600px;
}
#test {
  text-decoration: none;
}
#test:after {
  content: "";
  display: block;
  width: 0;
  transition: all 3s;
  border: 3px solid transparent;
}
#test:hover:after {
  width: 100%;
  border: 3px solid teal;
}
<div class="wrap">
  <a id="test" href="#">Some dummy-text for testing ...</a>
</div>