Search code examples
htmlcsshoverpseudo-elementpseudo-class

What's the purpose of `:hover::before`?


I'm looking at a html + css button, but I'm confused on why the before pseudo-element was used with the hover pseudo-class.

.anchor-style {
  font-size: 18px;
  letter-spacing: 2px;
  text-transform: uppercase;
  display: inline-block;
  text-align: center;
  width: 270px;
  font-weight: bold;
  padding: 14px 0px;
  border: 3px solid #ff0072;
  border-radius: 2px;
  position: relative;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.1);
}

.anchor-style::before {
  -webkit-transition: 0.5s all ease;
  transition: 0.5s all ease;
  position: absolute;
  top: 0;
  left: 50%;
  right: 50%;
  bottom: 0;
  opacity: 0;
  content: '';
  background-color: #ff0072;
  z-index: -2;
}

.anchor-style:hover::before {
  -webkit-transition: 0.5s all ease;
  transition: 0.5s all ease;
  left: 0;
  right: 0;
  opacity: 1;
}
<a class="anchor-style" target="_blank" href="http://www.infinity2o.com">
    Say Hi to My New Matches
</a>

There's already a regular style on the anchor tag, why would you need even more styling with a before pseudo-element?

I tried looking at the before pseudo-element documentation and understood that it would be useful for adding elements before each p tag... but I don't understand how it gets interpreted differently for the button.


Solution

  • It's for animation effect. The use of ::before is also cleaner.

    The ::before selector inserts something before the content of each selected element(s).

    So you can think of the ::before pseudo as an empty div. The following is equivalent without the ::before pseudo

    .anchor-style {
      font-size: 18px;
      letter-spacing: 2px;
      text-transform: uppercase;
      display: inline-block;
      text-align: center;
      width: 270px;
      font-weight: bold;
      padding: 14px 0px;
      border: 3px solid #ff0072;
      border-radius: 2px;
      position: relative;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.1);
    }
    
    .before {
      -webkit-transition: 0.5s all ease;
      transition: 0.5s all ease;
      position: absolute;
      top: 0;
      left: 50%;
      right: 50%;
      bottom: 0;
      opacity: 0;
      content: '';
      background-color: #ff0072;
      z-index: -2;
    }
    
    .anchor-style:hover > .before {
      -webkit-transition: 0.5s all ease;
      transition: 0.5s all ease;
      left: 0;
      right: 0;
      opacity: 1;
    }
    <a class="anchor-style" target="_blank" href="http://www.infinity2o.com">
        <div class="before"></div>
        Say Hi to My New Matches
    </a>