:: hover :: before的目的是什么?

时间:2018-08-15 19:59:31

标签: html css hover pseudo-element pseudo-class

我正在看一个html + css按钮,但是我对为什么将以前的伪元素与悬停伪类一起使用感到困惑。

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

anchor标签上已经有常规样式,为什么您需要使用before伪元素进行更多样式设置?

我尝试查看伪元素之前的文档,并且了解到在每个p标签之前添加元素会很有用...但是我不明白按钮的含义如何不同。

1 个答案:

答案 0 :(得分:3)

用于动画效果。 ::before的使用也更清洁。

  

:: before选择器在每个选定元素的内容之前插入一些内容。

因此,您可以将::before伪指令视为空的div。以下是等效的,没有::before

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

相关问题