Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to apply multiple CSS styles in a batch to avoid multiple reflows?

I know that altering element's style via JavaScript directly will cause a reflow. However, I was wondering if it is possible to alter multiple style values in a batch with only one reflow?

like image 777
Tower Avatar asked Nov 17 '10 17:11

Tower


People also ask

How do I apply multiple CSS styles on a single element?

You can apply multiple CSS property or value pairs for styling the element by separating each one with a semicolon within the style attribute. You should use inline CSS styles sparingly because it mixes the content marked by HTML with the presentation done using CSS.

Is it OK to have multiple CSS files?

Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword.

Can we link multiple stylesheets to a single page?

Yes, you can include multiple style sheets, but you need to label them as alternate style sheets and give the user some way to activate them using JavaScript - perhaps by clicking a link.


1 Answers

Not directly but there are some good suggestions on minimising the impact of reflows here:

http://dev.opera.com/articles/view/efficient-javascript/?page=3

In short, try something like this:

The second approach is to define a new style attribute for the element, instead of assigning styles one by one. Most often this is suited to dynamic changes such as animations, where the new styles cannot be known in advance. This is done using either the cssText property of the style object, or by using setAttribute. Internet Explorer does not allow the second version, and needs the first. Some older browsers, including Opera 8, need the second approach, and do not understand the first. So the easy way is to check if the first version is supported and use that, then fall back to the second if not.

var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
  'color: ' + newColor + ';' +
  'border: ' + newBorder + ';';
if( typeof( posElem.style.cssText ) != 'undefined' ) {
  posElem.style.cssText = newStyle; // Use += to preserve existing styles
} else {
  posElem.setAttribute('style',newStyle);
}
like image 69
Basic Avatar answered Oct 11 '22 20:10

Basic