In this example, I'm trying to make the parent element more transparent without changing the opacity of the child elements.
<div> <div className="larger-box"> <div className = "smaller-box"> </div> </div>
This is my current CSS style:
.larger-box{ width: 10rem; height: 10rem; background-color: red; } .smaller-box{ width: 2rem; height: 2rem; background-color: green; opacity: 1 !important; }
Is it possible to achieve this effect in CSS?
P粉0879514422023-09-10 13:25:43
You can use CSS not
.
.larger-box:not(.smaller-box) { width: 10rem; height: 10rem; background-color: red; } .smaller-box { width: 2rem; height: 2rem; background-color: green; }
P粉3156805652023-09-10 13:20:59
Children will always be affected by the opacity of their parent, so the easiest way to give them different opacity is to make them sibling elements and position the second element absolutely above the first , thus giving each element its own opacity. Please note the position: relative of the parent wrapping div.
Here I have some text displayed behind a red div with a green div above it, as if it were a child element, but in fact it is a sibling element and therefore is not affected by the opacity of the red div Influence. So the text shows through the red div, but not the green div.
.wrapper{ width: 10rem; height: 10rem; position: relative; } p { padding: 8px} .larger-box{ position: absolute; top: 0; left:0; width: 10rem; height: 10rem; background-color: red; opacity: 0.3 } .smaller-box{ width: 2rem; height: 2rem; background-color: green; opacity: 1; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
<div class="wrapper"> <p>Lorem ipsum dolor sit amet. Sit dicta tempore id quas delectus estitier at voluptatem voluptas sit culpa iste ea voluptatum vero!</p> <div class="larger-box"></div> <div class = "smaller-box"></div> </div>