12

Is it possible to apply CSS transitions inline (in the DOM), without using Pseudo Selector or using JS to add and change a property class on the dom? .

#target{
  width: 100px;
  height:100px;
  background-color:red;
}
<div id="target" style="transition: opacity 1s linear;"></div>
Radex
  • 7,815
  • 23
  • 54
  • 86

2 Answers2

10

Transitions need a changing value to produce any effect. This is usually achieved, as you mentioned, by toggling a class or using a pseudo selector.

If you want your "transition" to happen without any changing values, you need to use an animation:

#target{
  width: 100px;
  height:100px;
  background-color:red;
}

@keyframes fadeMe {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<div id="target" style="animation: fadeMe 2s;"></div>

I'm not sure why you would need to do this inline though.

Turnip
  • 35,836
  • 15
  • 89
  • 111
  • 1
    A great reason to do this is for cut and paste HTML (for example, to provide an inline advertisement). – Sablefoste Nov 20 '17 at 15:38
  • 5
    A reason for needing to do this inline is because you're writing this using a wiki that doesn't allow any other method. – David Smith Mar 29 '18 at 17:01
  • 3
    Another reason is when working with dynamic values from javascript like width for example. – frank Oct 26 '18 at 11:22
4

Combining with inline javascript you can achieve that, try this one:

#target{
  width: 100px;
  height:100px;
  background-color:red;  
}
<div id="target" style="transition: all 4s linear;" onclick="this.style.opacity = '.3'">click me</div>
RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21
  • It seems to work with just about any kind of DOM update, not limited to inline javascript. I've just verified transitions working in Chrome using ReactJS to update inline styles in the render() method. I don't know if there are limitations. – Eloff Sep 14 '17 at 18:52