0

I have a white star and an image. Everytime the image is hovered I change the opacity but I don't understand why my star disappear.

Run the example below, set your mouse hover the image and check for yourself. The opacity effect is just in the image, why is making my white star disappear?

figure {
  position: relative;
  border: thin #c0c0c0 solid;
  display: flex;
  flex-flow: column;
  padding: 5px;
  max-width: 220px;
  margin: auto;
}

icon-star {
  position: absolute;
  font-size: 50px;
  color: white;
}

img {
  max-width: 220px;
  max-height: 150px;
}

img:hover {
  opacity: .7;
}

figcaption {
  background-color: #222;
  color: #fff;
  font: italic smaller sans-serif;
  padding: 3px;
  text-align: center;
}
<figure>
  <icon-star></icon-star>
  <img src="https://interactive-examples.mdn.mozilla.net/media/examples/elephant-660-480.jpg" alt="Elephant at sunset">
  <figcaption>An elephant at sunset</figcaption>
</figure>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Chumpocomon
  • 661
  • 1
  • 6
  • 12

1 Answers1

2

Add z-index to star and it should work.

figure {
    position: relative;
    border: thin #c0c0c0 solid;
    display: flex;
    flex-flow: column;
    padding: 5px;
    max-width: 220px;
    margin: auto;
}

icon-star {
    position: absolute;
    font-size: 50px;
    color: white;
    z-index: 1;
}

img {
    max-width: 220px;
    max-height: 150px;
}

img:hover {
    opacity: .7;
}

figcaption {
    background-color: #222;
    color: #fff;
    font: italic smaller sans-serif;
    padding: 3px;
    text-align: center;
}
<figure>
    <icon-star></icon-star>
    <img src="https://interactive-examples.mdn.mozilla.net/media/examples/elephant-660-480.jpg" alt="Elephant at sunset">
    <figcaption>An elephant at sunset</figcaption>
</figure>
Tigran
  • 632
  • 1
  • 5
  • 21
  • and if you want to change the image opacity even if the star is hovered, you can also do that: `icon-star:hover + img { opacity: .7; }` – Ahmad Nawaz Khan May 09 '20 at 13:26
  • Thank you so much Ahmand! but if my `` is over my `` why I need to set it in CSS with `z-index: 1`? – Chumpocomon May 09 '20 at 15:53
  • 1
    @Chumpocomon it has nothing to do with position absolute, it doesn't matter if your icon is over another image. The reason it wasn't shown was because the `opacity` property with a value less than 1 cause stacking context. Stacking contexts affect z-indexes. Since you didn't specify z-indexes manually, they were being auto-assigned, and img had a higher value than icon-star because it came later in the markup. [stacking context](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context) – Ahmad Nawaz Khan May 09 '20 at 16:12