Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CSS, is [class][class] faster than [element][class]?

I know this is being picky but I'm working with an editor, which lints CSS and constantly complains

don't use adjoining classes > e.g.  .foo.bar

I'm ignoring the warnings, but it made me curious and can't find anything on it. Say I have:

  <ul class="foo bar"></ul>

which CSS selector is faster:

  ul.foo
  .bar.foo

I know selectors work right to left, so in both cases foo will be selected first, after which the browser has to find to find all ul in the selection(?) or all .bar elements(?).

Question:
In CSS, is [class][class] faster than [element][class]?

Thanks!

like image 804
frequent Avatar asked Sep 05 '14 12:09

frequent


2 Answers

Just for the sake of completeness: why does css lint complain?
Answer: Adjoining classes won't work for some very old browsers.

Quote from http://csslint.net/about.html:

Don't use adjoining classes

Adjoining classes look like .foo.bar. While technically allowed in CSS, these aren't handled properly by Internet Explorer 6 and earlier.

like image 75
sillyslux Avatar answered Oct 16 '22 12:10

sillyslux


I think the general rule, and one that I've noticed myself is that it would be slightly quicker to use .class .class, although it would depend on the page itself (and I suppose what styles are being applied to an extent).

The speed of different selectors are generally agreed to be (from quickest to slowest);

ID -> Class -> Type -> Adjacent -> Child -> Descendant -> Universal -> Attribute -> Pseudo

Personally, and I suppose from a markup point of view too, I would also find it more advantageous to to use a class to select the first element. It avoids the possibility that an element of the same type could be affected by your CSS if one was to be added in the future.

This also then complies with a lot of the CSS writing guides which say that it makes more sense to use classes for styling purposes.

I've also remembered a good article which covers CSS efficiency. I'm hoping that article agrees with me now as I haven't read it for a while. Somewhere on the site they also look at the Block Element Modifier technique of writing CSS too, which is an interesting read and a nice starting place if you want to structure your CSS more efficiently (although it takes a bit of getting your head around the first time).

like image 31
thecraighammond Avatar answered Oct 16 '22 12:10

thecraighammond