-1

I want to do make "World!" appear at 100% opacity when hovered over. But it doesn't work. However, if you swap the two numbers and make the opacity of .header=1 and .world:hover=0.5 the code works. So the :hover works when trying to reduce opacity, but not when trying to increase it. Does that mean 100% opacity of child is equal to the assigned opacity of the parent? Any way to fix that?

.header {
  opacity: 0.5;
}

.world:hover {
  opacity: 1;
}
<div class="header">
  <h1>Hello <span class="world">World!</span></h1>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
Ranindu
  • 1
  • 4

3 Answers3

3

Instead of using opacity, use color and rgba:

.header {
  color: rgba(0, 0, 0, 0.5);
}

.world:hover {
  color: rgba(0, 0, 0, 1);
}
<div class="header">
  <h1>Hello <span class="world">World!</span></h1>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Hey thanks, this worked like a charm! Do you know why using opacity does not work in this case? My guess is when you set the parent to 50% opacity, it becomes the default value for 100% opacity of the child. Of course, I might be mistaken. – Ranindu Sep 23 '20 at 17:41
2

Set world opacity for normal and hover

.world {
  opacity: 0.5;
}
.world:hover {
  opacity: 1;
}
Brian Wiltshire
  • 447
  • 4
  • 15
0

Let's clear a few things out of the way the property opacity is not inherited.

This means if you apply it to the parent the child will not receive it.

In your case, you applied opacity: 0.5 to .header which is the parent. This means the <h1> and <span> elements still have the opacity of 1 that's why every time you hovered over it you could not see the difference since it has been getting reset to 1 every time.

So give your span an opacity:0.5 then hover over it again and you will see a difference.

.world {
  opacity: 0.5;
}

.heading:hover .world {
  opacity: 1;
}
<div class="header">
  <h1 class="heading">Hello <span class="world">World!</span></h1>
</div>

I also think the best option is to use colors since it is easier to change their opacity using rbga

Ahmad Dalao
  • 1,968
  • 1
  • 8
  • 14
  • Hey thank you, but why this didn't work for me is because in my original code, all of "Hello World!" is at 0.5 opacity. So when that happens it's not possible to get "World!" to it's original opacity. Eg: `.header { opacity: 0.5; }` `.world {opacity: 1}` What I wanted was the whole thing to be at 50% opacity but to light up the words in my `` when I hovered over it. – Ranindu Sep 23 '20 at 17:52
  • As I mentioned when you gave `opacity: 0.5` to the `header` it's the only element that has opacity right now. The children do still have their opacity at 1. That's why it's kinda impossible to light the word in the `span` since the parent has an `opacity of 0.5`. Therefore I said you should use ` color` and use `rgba` with it to to set the color and that makes it look like it's lightening up on hover. – Ahmad Dalao Sep 23 '20 at 18:36