AntoineGGG
2 min readApr 16, 2021

--

CSS: Remove opacity inheritance from parent to children

Photo by 𝓴𝓘𝓡𝓚 𝕝𝔸𝕀 on Unsplash

This morning, I encountered a situation where I needed to add an image to the background of my Calendar page. However, I was a bit confused about how to prevent the opacity from being inherited by the child elements. Fortunately, I found a solution to resolve this issue. Here’s how you can fix it!

Html Layout:

<div className="main-container">
<div className="my-calendar">
</div>
</div>

(S)CSS Tricks :

.main-container {
position: relative;
height: 100%;
&::before {
content: '';
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
background: url('../../images/myBackgroundPics.jpg');
background-size: contain;
opacity: 0.15;
}
.my-calendar {
position: relative*
}
}

To address the issue of opacity inheritance, you can follow these steps:

  1. Begin by setting the position of the container element to relative.
  2. Create a pseudo-element using ::before with empty content. Apply an absolute position to the pseudo-element, and set the top, right, bottom, and left values to 0px. This ensures that the pseudo-element covers the entire container, making it fullscreen.
  3. Adjust the background properties of the pseudo-element as needed to customize your image background.
  4. Set the desired opacity value for the pseudo-element.
  5. Lastly, apply a relative position to the child elements within the container to prevent the inheritance of opacity.

By implementing these steps, you should be able to resolve the issue of opacity inheritance and achieve the desired effect for your Calendar background. I hope this solution proves helpful to you!

--

--