173

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?

5
  • I just now realized this would be better suited for Webmasters. Would there be a better place to post this?
    – ian5v
    Commented Feb 27, 2012 at 1:42
  • 12
    Right here is good.
    – Blender
    Commented Feb 27, 2012 at 1: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
    Commented Feb 27, 2012 at 2: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
    Commented Mar 5, 2012 at 1:53
  • those brackets are for attribute selectors: 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
    Commented Feb 22, 2016 at 15:35

11 Answers 11

175

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.

9
  • 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
    Commented Feb 27, 2012 at 2:16
  • 3
    So do stylesheets load the same way as elements, the last taking precedence if they are of the same specificity?
    – ian5v
    Commented Mar 5, 2012 at 1: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
    Commented Sep 19, 2014 at 7:38
  • 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.
    – user149341
    Commented Apr 3, 2016 at 2: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. Commented Jan 15, 2017 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.

2
  • 1
    See my comment on the question regarding that last selector.
    – BoltClock
    Commented Feb 27, 2012 at 2:14
  • 2
    The specificity rule make things harder when we need to override un-editable stylesheet!
    – Ari
    Commented Jul 2, 2015 at 14:37
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

1
  • 4
    So you should add the most specific CSS last.
    – live-love
    Commented Oct 30, 2014 at 16:37
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;

2
  • 2
    Hi. In my case the first defined .css is loaded last. Are they applied in order they are loaded or in order they are defined? Commented Dec 13, 2017 at 13:09
  • Thanks, this is exactly the explanation I was looking for. Commented Dec 15, 2018 at 21:04
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

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.

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/

1
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

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).

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.

3
  • Consider the case for alternate nearly identifcal style sheets loaded from the <head> 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. Commented Mar 10, 2019 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
    Commented Dec 18, 2019 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
    Commented Apr 15, 2020 at 19:38
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.