Suppose I have two files containing styles, a.css and b.css. I import them into my page in the <head>
section. Both of these external files define a style for the class .someclass
. Which one takes precedence? Is there any guarantee based on the order of the imports for css files that will state which style should be used?
views:
47answers:
1
+8
A:
They are cascading style sheets. Later definitions with the same specificity override earlier ones. More specific definitions take precedence over less specific definitions.
You can find exactly how the standard defines it (for CSS2) at http://www.w3.org/TR/CSS21/cascade.html.
tvanfosson
2010-05-12 13:54:16
http://www.w3.org/TR/CSS21/cascade.html#specificity
David Dorward
2010-05-12 13:55:49
@David -- thanks, I had just been looking for that link to add to my answer.
tvanfosson
2010-05-12 13:58:42
@David: I see that external style sheets' styles are overridden by styles defined in <style> blocks on the page are overridden by styles defined in an element style attribute. But I don't see where it specifies how duplicate styles of the same type as described above are to be handled.
RenderIn
2010-05-12 14:01:24
@Renderln Check section 6.4.1. "if two declarations have the same weight, origin and specificity, the latter specified wins."
ghoppe
2010-05-12 14:04:56
@ghoppe Thanks... that's the behavior I've been seeing but I wanted to make sure it was guaranteed.
RenderIn
2010-05-12 14:07:36
Where does it say <style> overrides external stylesheets?
David Dorward
2010-05-12 14:08:17
Actually, let me take that back. I still see a conflicting statement here: http://www.w3.org/TR/REC-html40/present/styles.html#h-14.3.2It says "If two or more LINK elements specify a preferred style sheet, the first one takes precedence." How does this reconcile with 6.4.1 of the above specification?
RenderIn
2010-05-12 14:19:43
@David I think he was confused by the example in section 6.4.3. It only works that way because <style> is typically declared after the style sheets, so given the same weight, origin and specificity <style> blocks will override the style sheet declarations.
ghoppe
2010-05-12 14:21:07
@Renderln That rule applies to preferred style sheets. They are enabled and disabled as a group, thus have different rules.
ghoppe
2010-05-12 14:24:28
@ghoppe Hadn't knowingly come across preferred stylesheets before... thanks for the info.
RenderIn
2010-05-12 14:27:09
@Renderln Read more about how to use them here: http://www.alistapart.com/articles/alternate/
ghoppe
2010-05-12 14:28:03