Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect of applying CSS class name that does not exist

Tags:

jquery

css

Does it have an adverse effect on a browser's performance to assign class name to an element's css class attribute if the class never actually defined?

It is not unusual to use class names for selectors with JQuery. I normally use a class that is only ever used to select elements and never actually define the class anyplace.

I am assuming most browsers would look for the css class definition and you could somehow short circuit the search if the style was defined?

It is my understanding that the css styles are compiled together before the page elements are rendered. This is why it is important to keep all CSS definitions together and not split them up with script tags since it causes most browsers to recompile the CSS each time when they are intermingled with other definitions. The implications of this can be severe enough to allow the page to render before the style is applied.

However, in practice, I would guess the performance difference between defining or not defining a CSS class is negligible if any.

like image 447
Rich M Avatar asked Mar 12 '12 04:03

Rich M


2 Answers

The easiest way to think about this is to remember that CSS is applied to the HTML, not the HTML calling the CSS selectors.

When the browser parses the CSS file, it reads a selector right to left to see where to apply the styles. For example .foo ul { } would check for all ul tags's on a page, and then check to see if they are contained within .foo. Because it is parsed in this manner, extra, unused classes in your HTML don't matter. It is only checking for ids and classes specified in the CSS.

like image 105
Brian Hough Avatar answered Nov 09 '22 14:11

Brian Hough


As the class attribute is an HTML attribute, it can be inserted with no problems if it isn't called by the CSS or Javascript. It can sit there quite happily on its own with no side effects. It doesn't need to be selected by CSS, it can be used by JS alone.

This article might help you understand more:

class (HTML attribute) @ sitepoint.com

like image 37
Kyle Avatar answered Nov 09 '22 13:11

Kyle