【问题标题】:What's the purpose of `:hover::before`?`:hover::before` 的目的是什么?
【发布时间】:2019-01-22 17:43:29
【问题描述】:

我正在查看一个 html + css 按钮,但我对为什么将 before 伪元素与 hover 伪类一起使用感到困惑。

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

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

我尝试查看之前的伪元素文档,并了解到它对于在每个 p 标签之前添加元素很有用......但我不明白它是如何被不同地解释为按钮的。

【问题讨论】:

  • 伪元素正在创建背景效果,只需阅读CSS并检查每个属性,更改它们,测试等,您就会明白......顺便说一句我们可以不用
  • 您可以尝试在没有:before 的情况下应用样式并比较结果。
  • 如果你要否决我的问题,至少告诉我为什么
  • @Hunter690 仅供参考,您可能被正在查看您问题的第一部分并认为它过于主观或会提供主观答案的人投反对票。 SO 希望所有问题都非常具体,并带有明确的问题,并提示非常具体的数据驱动的答案。

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


【解决方案1】:

用于动画效果。 ::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>

【讨论】:

  • 谢谢你的例子;为什么需要: .before 类。难道你不能把.anchor-style:hover &gt; .before改成.anchor-style:hover &gt; div,然后把.before中所有多余的东西移到.anchor-style:hover &gt; div吗?
  • @Hunter690 当然,before 课程只是为了演示。
  • 哦,好吧,但你为什么不能只做.anchor-style:hover {} 并把所有这些东西都包括在内?
  • @Hunter690,因为当您悬停时,您希望定位 div 并对其应用样式。是 div 产生了 background-fading 效果。
猜你喜欢
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 2018-04-25
  • 1970-01-01
  • 2011-11-11
  • 2011-08-29
  • 2015-01-01
相关资源
最近更新 更多