How can I apply a style only to the parent element without affecting the styles of the child elements?
P粉827121558
P粉827121558 2023-09-09 16:47:14
0
2
510

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粉827121558
P粉827121558

reply all(2)
P粉087951442

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粉315680565

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template