Different opacity element within a div

Viewed 8338

I need to change opacity of an element within a div, to give it more opacity than the parent. How can I give the .solid a full opacity (="1"), without pre-processors?

.half-faded {
  opacity:0.3;
  border:1px solid black;
  width:200px;
  display:flex;
  justify-content:space-around;
}
.solid {
  opacity:1; /* doesn't help */
  opacity:2; /* twice doesn't help */
}
<div class="half-faded">
  <span class="one">One</span>
  <span class="two">Two</span>
  <span class="solid">Solid</span>
  <span class="four">Four</span>
</div>

4 Answers

If .half-faded has multiple elements (not just spans), you could do:

.half-faded > * {
  opacity: .3;
}

.half-faded > .solid {
  opacity: 1;
}

[Edit]

The only way to do what you asked in the comment is to wrap the "Solid" text inside a <span> for example, as shown in the snippet below. The reason is that the .half-faded > .solid rule turns the opacity of the .solid elements back to 1, so we would have to turn down the opacity of the text outside the .biz element back to 0.3, however there's no CSS rule to match text nodes, therefore you need to have the text inside an element.

If you're able to change how the markup is built, I think it'd be easier to change the way it's being built.

.half-faded > * {
  opacity: .3;
  display: block;
}

.half-faded > .solid {
  opacity: 1;
}

.half-faded > .solid > span {
  opacity: .3;
}
<div class="half-faded">
  <div>Not solid</div>
  <a class="solid">Solid</a>
  <span class="solid">
    <span>Inside solid but not solid</span>
    <a href="#" class="biz">Solid business</a>  
  </span>
</div>

You could do:

.half-faded {
  border: 1px solid rgba(0, 0, 0, 0.3);
  width: 200px;
  display: flex;
  justify-content: space-around;
}

.half-faded * {
  opacity: 0.3;
}

.half-faded .solid {
  opacity: 1;
}
<div class="half-faded">
  <span class="one">One</span>
  <span class="two">Two</span>
  <span class="solid">Solid</span>
  <span class="four">Four</span>
  <div>other</div>
</div>

Please see my comment.

The black background is to show that it is see-thru.

body{
background-color:black;
}

.half-faded {
  background-color:rgba(255,255,255,0.3);
  border:1px solid black;
  width:200px;
  display:flex;
  justify-content:space-around;
}

.half-faded span{
opacity:0.3;
}
.solid {
  opacity:1 !important;
}
<div class="half-faded">
  <span class="one">One</span>
  <span class="two">Two</span>
  <span class="solid">Solid</span>
  <span class="four">Four</span>
</div>

opacity property can only accept numbers between 0 and 1, so opacity: 2 is invalid. The problem is that you're trying to change opacity of child element (it's already have opacity: 1). The increasing opacity of child element will not solve the issue, you need to change opacity property of .half-faded element.

Related