Warm tip: This article is reproduced from stackoverflow.com, please click
animation css

Multi-Line link animation on :before

发布于 2020-03-31 22:55:24

Like in the question, I have a code

How to make this effect work on many text lines and not as it is now - the effect appears only in 1 of e.g. 2 text lines (like example)

:root {
--00a3a3: #00a3a3;
}

a {
position: relative;
text-decoration: none; /* For Example */
}

a:before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: var(--00a3a3);
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}

a:hover:before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
<a href="#">test</a>
<br>
<br>
<a href="#">test
<br>
test2
</a>
Questioner
MAJO
Viewed
21
thingEvery 2020-02-01 18:13

Get rid of the ::before. Instead apply a background-image to the <a>.

:root {
--00a3a3: #00a3a3;
}

a {
position: relative;
text-decoration: none; /* For Example */
background-image: linear-gradient(#00a3a3, #00a3a3);
background-position: 50% 100%;
background-repeat: no-repeat;
background-size: 0% 2px;
transition: background-size .3s;
}

a:hover {
background-size: 100% 2px;
}
<a href="#">test</a>
<br>
<br>
<a href="#">test
<br>
test2
</a>

Edit: The problem is that the :before pseudo-element doesn't know that your <a> is two lines. It's just adding a new block element inside it and taking the shape you give it.

If you know that your links will always be two lines, you might be able to get away with using an :after for the second line, like this:

:root {
  --00a3a3: #00a3a3;
}

a {
  position: relative;
  text-decoration: none;
  /* For Example */
}

a:before,
a:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  left: 0;
  background-color: var(--00a3a3);
  visibility: hidden;
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transition: all 0.3s ease-in-out 0s;
  transition: all 0.3s ease-in-out 0s;
}

a:before {
  bottom: 0;
}

a:after {
  bottom: 1em;
}

a:hover:before,
a:hover:after {
  visibility: visible;
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}
<a href="#">test</a>
<br>
<br>
<a href="#">test
<br>
test2
</a>

(But you're probably better off restructuring your code to remove the :before.)