0

I have a pretty simple link that is shown as block with a little green star in the corner.

JsFiddle

I want to make it so that when you hover over the link, the link itself goes slightly transparent, but the :before pseudo selector won't be affected.

I looked at some questions on this but for some reason I could not get their solutions to work. Is this possible? I am uncertain if I am simply writing the wrong CSS selectors.

EDIT: Ideally I want to be able to handle both background-images and background colors.

Community
  • 1
  • 1
aug
  • 11,138
  • 9
  • 72
  • 93

1 Answers1

6

Use rgba(r, g, b, a) values instead.

On :hover change the alpha value.

a {
  display: block;
  width: 100px;
  height: 100px;
  background: rgba(255, 0, 0, 1);
  position: relative;
}
a:before {
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  content: "★";
  background: green;
}
a:hover {
  background: rgba(255, 0, 0, 0.5);
}
<a href="www.google.com"></a>

If you are dealing with images, you can't actually change the opacity on an image without affect the parent. If you really want to use a pseudo selector, you can create a container around the element, attach the :before selector to that and apply the hover state only on the inner element.

div {
position: relative;
}

a {
  display: block;
  width: 200px;
  height: 200px;
  background: url(http://suptg.thisisnotatrueending.com/archive/19343530/images/1338832441002.png);
}

div:before {
  position: absolute;
  top:0;
  left:0;
  color:white;
  content:"★";
  background: green;
  z-index: 2;
}

a:hover {
 opacity: 0.5;   
}
<div>
    <a href="www.google.com"></a>
</div>

Here's an example jsFiddle

aug
  • 11,138
  • 9
  • 72
  • 93
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
  • Wow so fast! Any explanation as to why this works? I'm still uncertain why RGBA would not affect the `:before` selector but using hex would. – aug Jan 08 '15 at 18:38
  • @aug - Because here we are changing the `background-color` not the `opacity`. – Weafs.py Jan 08 '15 at 18:38
  • @chipChoclate.py oh I see. Just wondering, is there a way to do it with `opacity`? I was also hoping to handle situations where the background is an image. Apologies for the oversimplification because that was another use case I was hoping to address. – aug Jan 08 '15 at 18:40
  • 2
    @aug - The answer is no, it's not possible to change an element's `opacity` without affecting its :pseudo-element unless you use another element instead of a :pseudo-element. – Weafs.py Jan 08 '15 at 18:42
  • 1
    @chipChoclate.py Actually after taking in what you said, I figured you could create a container around the element you wanted to apply a hover over and apply the `:before` selector on that if you REALLY wanted to use opacity. Not sure if I wanna go this route but thought it was worth adding. I updated your answer :) Appreciate all the help. – aug Jan 08 '15 at 18:57