Search code examples
htmlcssopacity

How can I change opacity without affecting other HTML elements?


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>


Solution

  • 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>