避免将样式应用于:使用后:悬停

时间:2015-12-02 16:30:01

标签: jquery css css3 pseudo-element css-content

我正在使用:之后允许自己使用半径和渐变的边框,例如:

 #main .element {
      border-radius: 10px;
      background: #FFF;
    }

 #main .element:after {
      border-radius: 10px;
      background: linear-gradient(red, blue);
      top: -7px;
      bottom: -7px;
      left: -7px;
      right: -7px;
      z-index:-1;
    }

我希望有问题的元素在悬停时改变背景颜色,例如:

#main .element:hover {
  background: #F00;
}

问题是:after伪元素也被选中了,它的背景也被改变了 - 我不希望在悬停在元素上之后影响样式 - 我希望边框保持其背景颜色。 有关如何做到这一点的任何建议?我更喜欢使用CSS,但如果需要,我不反对使用jquery。感谢

1 个答案:

答案 0 :(得分:3)

问题不在于:after是从父级继承样式,而是this jsfiddle shows
你的问题是:after的css缺少几个关键属性:

#main .element:after {
  /* :before and :after elements *must* have `content` set, even if it is empty*/
  content: "";
  border-radius: 10px;
  background: linear-gradient(red, blue);
  /* :after also doesn't have any size, since you never position it. Without a non-static position, top, bottom, etc. are ignored*/
  position:absolute;
  top: -7px;
  bottom: -7px;
  left: -7px;
  right: -7px;
  z-index: -1;
}