171

In an HTML header, I've got this:

<head>
<title>Title</title>
<link href="styles.css" rel="stylesheet" type="text/css"/>
<link href="master.css" rel="stylesheet" type="text/css"/>

styles.css is my page-specific sheet. master.css is a sheet I use on each of my projects to override browser defaults. Which of these stylesheets takes priority? Example: first sheet contains specific

body { margin:10px; }

And associated borders, but the second contains my resets of

html, body:not(input="button") {
    margin: 0px;
    padding: 0px;
    border: 0px;
}

In essence, does the cascading element of CSS work the same in terms of stylesheet references as it does in typical CSS functions? Meaning that the last line is the one displayed?

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
ian5v
  • 2,078
  • 2
  • 18
  • 20
  • I just now realized this would be better suited for Webmasters. Would there be a better place to post this? – ian5v Feb 27 '12 at 01:42
  • 12
    Right here is good. – Blender Feb 27 '12 at 01:43
  • 5
    `body:not(input="button")` is not a valid selector by the way. You probably meant to split it into `body, input:not([type="button"])`. – BoltClock Feb 27 '12 at 02:12
  • That's interesting. I don't believe I've seen such syntax before. I'm still new, but those double brackets are foreign to me. – ian5v Mar 05 '12 at 01:53
  • those brackets are for attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors @topic: probably you want to switch the order of the stylesheets: Your general `master.css` should load first, then it's way easier to overrule the master-styles in your `styles.css`. – grilly Feb 22 '16 at 15:35

11 Answers11

174

The rules for CSS rule cascading are complex -- rather than trying to paraphrase them badly, I'll simply refer you to the spec:

http://www.w3.org/TR/2011/REC-CSS2-20110607/cascade.html#cascade

In short: more specific rules override more general ones. Specificity is defined based on how many IDs, classes, and element names are involved, as well as whether the !important declaration was used. When multiple rules of the same "specificity level" exist, whichever one appears last wins.

  • 2
    Then there's no specific rule as to in what order stylesheets load? I understand how CSS displays in terms of specificity, but then I'll assume my master sheet will load unless overridden. – ian5v Feb 27 '12 at 01:49
  • 1
    I *believe* that stylesheets are treated as if they're loaded in the order that they're linked in the HTML (even if they actually load out of order), but I'm not certain. –  Feb 27 '12 at 01:51
  • Something I read earlier suggested the opposite, but I can't say for sure. – ian5v Feb 27 '12 at 01:53
  • 12
    Actually, `!important` participates directly in the cascade, and has nothing to do with specificity. Specificity is related to selectors, whereas `!important` is used with property declarations. (So you're right in saying that the rules are complex! ;) – BoltClock Feb 27 '12 at 02:16
  • 3
    So do stylesheets load the same way as elements, the last taking precedence if they are of the same specificity? – ian5v Mar 05 '12 at 01:54
  • 5
    @iananananan: Basically, the browser never sees CSS in terms of individual stylesheets. If there are multiple stylesheets, they are all treated as if they were one giant stylesheet, and rules are evaluated accordingly. – BoltClock Sep 19 '14 at 07:38
  • @BoltClock, see document.styleSheets. The browser definitely keeps each the stylesheet separate. – Sam Hobbs Apr 03 '16 at 02:02
  • 3
    @user34660 BoltClock's comment is from the perspective of CSS styling. You're correct that the stylesheets are kept separate in the DOM, but that separation doesn't affect how those styles get applied to anything. –  Apr 03 '16 at 02:14
  • 4
    Thank you for "When multiple rules of the same "specificity level" exist, whichever one appears last wins"! This was the piece of information that I needed. – Andrei Rînea Jan 15 '17 at 18:17
37

The most specific style is applied:

div#foo {
  color: blue; /* This one is applied to <div id="foo"></div> */
}

div {
  color: red;
}

If all of the selectors have the same specificity, then the most recent decleration is used:

div {
  color: red;
}

div {
  color: blue; /* This one is applied to <div id="foo"></div> */
}

In your case, body:not([input="button"]) is more specific so its styles are used.

Blender
  • 289,723
  • 53
  • 439
  • 496
27

Order does matter. The last declared value of multiple occurrence will be taken. Please see the same one I worked out: http://jsfiddle.net/Wtk67/

<div class="test">Hello World!!</div>


<style>
    .test{
        color:blue;
    }

    .test{
        color:red;
    }
</style>

If you interchange the order of .test{}, then you can see the HTML takes value of the last one declared in CSS

Just code
  • 13,553
  • 10
  • 51
  • 93
Roy M J
  • 6,926
  • 7
  • 51
  • 78
22

The last loading CSS is THE MASTER, which will override all css with same css settings

Example:

<head>
    <link rel="stylesheet" type="text/css" href="css/reset.css">
    <link rel="stylesheet" type="text/css" href="css/master.css">
</head>

reset.css

h1 {
    font-size: 20px;
}

master.css

h1 {
    font-size: 30px;
}

The output for the h1 tag will be font-size: 30px;

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Doodl
  • 247
  • 2
  • 7
9

Lets try to simplify the cascading rule with an example. The rules goes more specific to general.

  1. Applies rule of the ID's one first (over class and/or elements regardless of the order)
  2. Applies classes over elements regardless of order
  3. If no class or id, applies the generic ones
  4. Applies the last style in the order (declaration order based on file load order) for the same group/level.

Here is the css and html code;

<style>
    h2{
        color:darkblue;
    }
    #important{
        color:darkgreen;
    }
    .headline {
        color:red;
    }
    article {
        color:black;
        font-style:italic;
    }
    aside h2 {
        font-style:italic;
        color:darkorange;
    }
    article h2 {
        font-style: normal;
        color: purple;
    }
</style>

Here is the css style

<body>
<section>
    <div>
        <h2>Houston Chronicle News</h2>
        <article>
            <h2 class="headline" id="important">Latest Developments in your city</h2>
            <aside>
                <h2>Houston Local Advertisement Section</h2>
            </aside>
        </article>
    </div>

    <p>Next section</p>
</section>

Here is the result. No matter the order of style files or the style declaration, id="important" applies at the end (note the class="deadline" declared last but does not take any effect).

The <article> element contains <aside> element, however last declared style will take effect, in this case article h2 { .. } on third h2 element.

Here is the result on IE11: (Not enough rights to post image)DarkBlue: Houston Chronicle News, DarkGreen: Latest Developments in your city, Purple: Houston Local Advertisement Section, Black: Next section

enter image description here

Kagan Agun
  • 489
  • 1
  • 6
  • 7
6

It depends on both load order and the specificity of the actual rules applied to each style. Given the context of your question you want to load your general reset first, then the page specific. Then if youre still not seeing the intended effect you need to look into the specificity of the selectors involved as others have already pointed out.

prodigitalson
  • 60,050
  • 10
  • 100
  • 114
2

The best way is to use classes as much as possible. Avoid ID selectors (#) anyway. When you write selectors with just single classes, the CSS inheritance is way more easy follow.

Update: Read more about CSS specificity in this article: https://css-tricks.com/specifics-on-css-specificity/

Jeroen Ooms
  • 116
  • 5
1

I suspect from your question that you have duplicate selections, a master set, that goes for all pages, and a more specific set that you wish to override the master values for each individual page. If that is the case, then your order is correct. The Master is loaded first and the rules in subsequent file will take precedence (if they are identical or have the same weight). There is a highly recommended description of all rules at this website http://vanseodesign.com/css/css-specificity-inheritance-cascaade/ When I started with front end development, this page cleared up so many questions.

1

EDIT: Apr 2020, according to @LeeC's comment, this is not longer the case

Yes, it works the same as if they were in one sheet, however:

Load Order Matters!

<link href="styles.css" rel="stylesheet" type="text/css"/>
<link href="master.css" rel="stylesheet" type="text/css"/>

In the above code, there is no guarantee that master.css will load after styles.css. Therefore, if master.css is loaded quickly, and styles.css takes a while, styles.css will become the second stylesheet, and any rules of the same specificity from master.css will be overwritten.

Best to put all your rules into one sheet (and minify) before deploying.

n_i_c_k
  • 1,504
  • 10
  • 18
  • Consider the case for alternate _nearly identifcal_ style sheets loaded from the section of a page, one containing conditional _media_ attributes to load a styleheet specific to smartphones and tablets. In this case, the logic specified in _media_ must be strictly exclusive for each stylesheet if the load order is indeterminate. – Lindsay Haisley Mar 10 '19 at 23:21
  • 1
    @n_i_c_k Your answer is incorrect. The order of _declaration_ is what matters, not the _load_ order. I just tested this with Fiddler, by halting the download of `master.css`, and letting `styles.css` load fully. Then, I let `master.css` load. The "overlapping" style from `master.css` still applied--and the rendering was blocked until `master.css` loaded and was parsed. *Note*: I tried `rel=preload` on `master.css' (no halting) and that apparently alters its _declaration_ order by hoisting it above `styles.css`. – LeeC Dec 18 '19 at 19:19
  • Thanks @LeeC, I know at the time of writing my answer was correct, but I'll take your word for it that it's been fixed now and edit my answer. – n_i_c_k Apr 15 '20 at 19:38
1

It is the cascade that defines the precedence of declarations. I can recommend the official specification; this part of it is well-readable.

https://www.w3.org/TR/css-cascade-3/#cascading

The following have an effect on the sorting, in descending order of priority.

  1. A combination of origin, and importance:

    1. Transition declarations
    2. User agent’s declarations marked with !important
    3. User’s declarations marked with !important
    4. Page author’s declarations marked with !important
      1. Definitions on the element with style attribute
      2. Document-wide definitions
    5. Animation declarations
    6. Page author’s declarations
      1. Definitions on the element with style attribute
      2. Document-wide definitions
    7. User’s declarations
    8. User agent’s declarations
  2. If two declarations have the same origin and importance, the specifity, meaning how clearly the element is defined, comes into play, calculating a scoring.

    • 100 points for every identifier (#x34y)
    • 10 points for every class (.level)
    • 1 point for every element type (li)
    • 1 point for every pseudo-element (:hover) excluding :not

    For example, the selector main li + .red.red:not(:active) p > * has a specifity of 24.

  3. The order of appearance only plays a role if two definitions have the same origin, importance and specificity. Later definitions precede earlier definitions in the document (including imports).

Michael Schmid
  • 4,601
  • 1
  • 22
  • 22
0

I believe when executing the code, it is read top to bottom, meaning the last CSS link would be override similar styles in any style sheets above it.

For example, if you created two style sheets

<link rel="stylesheet" href="style1.css"> 
<link rel="stylesheet" href="style2.css">

and in both of these, you set the body background-color to two different colors - the color of the body in style2.css would take priority.

You could avoid the styling priority issue by using !IMPORTANT inside the class style you would like to take priority, or possibly re-arranging your <link> order.