Home > Software engineering >  Smooth CSS transition from position relative to position absolute with :hover::after
Smooth CSS transition from position relative to position absolute with :hover::after

Time:06-24

I am trying to build an underline under the nav menu on hover. I'm using the 'content' trick because I couldn't make what I wanted with just text decoration.

I want something like this but with a smooth transition.

Here's the CSS for it without transition because I couldn't make it work.

div {
  display: flex;
  align-items: center;
  color: #ab9b8c;
  font-size: 20px;
  letter-spacing: 1.5px;
  text-decoration: none;
  height: 100%;
  cursor: pointer;
  transition: height 2s;
  position: relative;
}

div:hover::after {
  content: '';
  position: absolute;
  bottom: -1px;
  width: 30px;
  height: 3px;
  border-radius: 200px;
  border: 1px solid #9f9182;
}
<div>test
  <div/>

CodePudding user response:

As Paulie_D mentioned, you can't do transitions on position attributes. See: https://www.w3schools.com/cssref/pr_class_position.asp "Animatable: no."

Several other attributes are fair game though. Here's one using the width and the border:

div {
  display: flex;
  align-items: center;
  color: #ab9b8c;
  font-size: 20px;
  letter-spacing: 1.5px;
  text-decoration: none;
  height: 100%;
  cursor: pointer;
  transition: height 2s;
  position: relative;
}

div::after {
  content: '';
  position: absolute;
  bottom: -1px;
  width: 0px;
  height: 3px;
  border-radius: 200px;
  border: 0px solid #9f9182;
  transition: all 0.2s linear;
}

div:hover::after {
  width: 30px;
  border: 1px solid #9f9182;
  transition: all 0.2s linear;
}
<div>test
</div>

Here's an opacity:

div {
  display: flex;
  align-items: center;
  color: #ab9b8c;
  font-size: 20px;
  letter-spacing: 1.5px;
  text-decoration: none;
  height: 100%;
  cursor: pointer;
  transition: height 2s;
  position: relative;
}

div::after {
  content: '';
  position: absolute;
  bottom: -1px;
  width: 30px;
  height: 3px;
  border-radius: 200px;
  border: 1px solid #9f9182;
  opacity: 0;
  transition: all 0.2s linear;
}

div:hover::after {
  opacity: 1;
  transition: all 0.2s linear;
}
<div>test
</div>

Here's both at once because why not:

div {
  display: flex;
  align-items: center;
  color: #ab9b8c;
  font-size: 20px;
  letter-spacing: 1.5px;
  text-decoration: none;
  height: 100%;
  cursor: pointer;
  transition: height 2s;
  position: relative;
}

div::after {
  content: '';
  position: absolute;
  bottom: -1px;
  width: 0px;
  height: 3px;
  border-radius: 200px;
  border: 0px solid #9f9182;
  opacity: 0;
  transition: all 0.2s linear;
}

div:hover::after {
  width: 30px;
  opacity: 1;
  border: 1px solid #9f9182;
  transition: all 0.2s linear;
}
<div>test
</div>

So on and so on

  • Related