Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS opacity to parent, but not child [duplicate]

Tags:

javascript

css

I have a sentence with a highlighted word:

I'm trying to make it so the class="special" is visible and the rest of the class="sentence" appears around it.

After a few seconds, I'm triggering this:

setTimeout(() => {
  document.getElementById("sentence-1").className += " fadeIn";
}, 2000)
.sentence {
  opacity: 0;
}
.special {
  opacity: 1;
}

.fadeIn{
  opacity: 1;
  transition: opacity 2s 2s;
}
<span id="sentence-1" class="sentence">This is the special <span id="special-1" class="special">word</span>, cool huh?</span>

Which in my mind says set the opacity of .sentence to 0 and the opacity of .special to 1 then fade in sentence when the javascript is triggered...

Instead, the whole thing fade in, and I can't make .special visible all the time.


Edits: I have access to either .class or #id for the parent and child element if that helps...
like image 996
Trees4theForest Avatar asked Jan 31 '26 05:01

Trees4theForest


2 Answers

You won't be able to do this with opacity because you cannot nest opaque elements within a transparent one. The net result is complete transparency.

What you can do instead is use an rgba colour value and transition the alpha channel.

For example

window.addEventListener('load', () =>
  document.querySelector(".sentence").classList.add("fadeIn"));
.sentence {
  color: rgba(0, 0, 0, 0);
  transition: color 2s 2s;
}
.special {
  color: #000;
}

.fadeIn {
  color: rgba(0, 0, 0, 1);
}
<span class="sentence">This is the special <span class="special">word</span>, cool huh?</span>

Note: I had to run the JS within the window load event to ensure the CSS applied correctly

like image 65
Phil Avatar answered Feb 02 '26 18:02

Phil


setTimeout(() => {
var x = document.getElementsByClassName('sentence');
var i;
for (i = 0; i < x.length; i++) 
{
   x[i].className += ' fadeIn'; // WITH space added
}
  

}, 2000)
.sentence {
  opacity: 0;
}
  
.fadeIn{
  opacity: 1;
  transition: opacity 2s 2s;
}
 <span class="sentence">This is the special </span>word
 <span class="sentence">
, cool huh?</span>
like image 24
Daveo Avatar answered Feb 02 '26 18:02

Daveo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!