0

So, I am trying to create a simple underline animation on hover, everything works fine but there's a small weird behavior that I don't get.

This code snippet doesn't work as expected. On hover it has no effect.

.underline {
    font-weight: bold;
    font-size: 2rem;
    position: relative;
}

.underline::before {
    pointer-events: none;
    position: absolute;
    content: "";
    width: 0%;
    height: 6px;
    background-color: black;
    left: 50%;
    bottom: 0;
    transition: all .4s ease-in-out;
}

.underline:hover {
    cursor: pointer;
}

.underline:hover .underline::before {
    height: 6px;
    width: 100%;
    left: 0;
}

body {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
<div class="underline">Know More</div>

But a small tweak i.e. wrapping .slider into a container .wrapper solves the problem. I don't get why.

.underline {
  font-family: cursive;
  font-weight: bold;
  font-size: 3rem;
  position: relative;
}

.underline::before {
  pointer-events: none;
  position: absolute;
  content: "";
  width: 0%;
  height: 6px;
  background-color: black;
  left: 50%;
  bottom: 0;
  transition: all .4s ease-in-out;
}

.underline:hover {
  cursor: pointer;
}

.wrapper:hover .underline::before {
  height: 6px;
  width: 100%;
  left: 0;
}

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="wrapper">
  <div class="underline">Know More</div>
</div>

So, .wrapper:hover .underline::before css selector works but .underline:hover .underline::before doesn't WHY?

1 Answers1

1

.underline:hover .underline::before looks for an element with class underline inside an element with class underline. It's a descendant selector. That doesn't match your document structure.

I'm not entirely sure what your goal is, but I'd bet that .underline:hover::before would do fine. See How to make a hover effect for pseudo elements?.

isherwood
  • 58,414
  • 16
  • 114
  • 157