Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack CSS Transitions using multiple classes without overriding

I want to use multiple classes to optionally add transitions. Instead of stacking, the previous is getting overridden.

.container { transition: margin .2s; }
.container.t-padding { transition: padding .2s; }

The problem: Property is overridden rather than stacking

http://jsfiddle.net/yz2J8/2/ (The problem)

My temporary solution: Add the previous transition to the rule

.container { transition: margin .2s; }
.container.t-padding { transition: padding .2s, margin .2s; }

http://jsfiddle.net/ZfQcp/6/ (My temporary solution)

What's a better solution??

How can I avoid having to create tons of rules to combine these?

like image 778
Michael Lewis Avatar asked Jun 02 '13 23:06

Michael Lewis


1 Answers

JavaScript could be a cleaner solution as you only need to have 1 CSS rule (the original rule).

If you know the position of you're rule you can do the following.

//First Save The Original Rule

var originalRule = document.styleSheets[0].cssRules[3].cssText;

//Save also the original Hover Rule

var originalHover = document.styleSheets[0].cssRules[4].cssText;

Now originalRule will contain this:

.container{
   ...
   transition: margin .2s;
   ...
}

And originalHover will contain this:

.container:hover{
   ...
   margin: 10px 0;
   ...
}

to simply add another transition effect, you can do the following.

document.styleSheets[0].cssRules[3].style.transitionProperty += ",background-color";
document.styleSheets[0].cssRules[4].style.transitionDuration += ",1s";

At this stage, both transitions will take effect.

If you want to only have the original transition, you can either add it manually or simply...

//Delete the Rule

document.styleSheets[0].deleteRule(3);

//Add the Original Rule Back Again

document.styleSheets[0].insertRule(originalRule,3);

If you do so, only the original transition (margin) will take effect, don't forget to also replace the originalHover rule to remove any other effects on hover.

Note:

For Chrome

document.styleSheets[0].cssRules[3].style.webkitTransitionProperty

For Firefox

document.styleSheets[0].cssRules[3].style.mozTransitionProperty

For IE insertRule and deleteRule do not work, there's these ones instead:

addRule , removeRule

LIVE DEMO FOR CHROME AND FIREFOX

like image 80
Ali Bassam Avatar answered Oct 07 '22 01:10

Ali Bassam