Search code examples
jquerycsspseudo-elementcss-content

Avoid applying style to :after when using :hover


I am using :after to allow myself a border with a radius and a gradient, like:

 #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;
    }

I want the element in question to change its background colour when it is being hovered over, like:

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

The problem is that the :after pseudo element gets selected too, and its background is also changed - I do not want the :after style to be effected when hovering over the element - I want the border to maintain its background colour. Any suggestions on how to do this? I would prefer to use CSS but I am not against using jquery if need be. Thanks


Solution

  • The problem is not the :after is inheriting the style from the parent, as this jsfiddle shows.
    Your problem is that the :after's css is missing a couple of key properties:

    #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;
    }