Bad Dobby
Bad Dobby

Reputation: 871

Making the width of pseudo a::after as the container

I'm trying to make a transition to some 'a' tags. And which is that when it is mouse hovered, the underline is slowly grow from the left to the right on its text string.

I figured that I should make it with pseudo of the a tag, I succeed to make a similar transition, but it has a problem that make me stuck.

.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>

I make the transition to change width of a::after from 0 to 100% but width 100% is rendered by the size of .test, not to the size of 'a'. So the length of underline doesn't fits to the text. It fits to the screen size.

I cannot understand that why a::after doesn't follow the size of its parent, a. And want to know how can I make a::after to follow the size of 'a'.

Upvotes: 3

Views: 485

Answers (2)

Temani Afif
Temani Afif

Reputation: 272590

Here is another idea without the use of pseudo element and without the issue of size:

.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>

Upvotes: 1

Stickers
Stickers

Reputation: 78676

You can either add:

.test {
  display: inline-block;
}

or

.test a {
  display: inline-block;
}

So that the size of the box matches the content.

.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>

Upvotes: 3

Related Questions