35

If I have two css files:

File 1:

.colorme
{
   background-color:Red;
}

File 2:

.colorme
{
   background-color:Green;
}

And have included them in a page, which one will take priority? I'm guessing the one that is loaded last? If so is there anyway to ensure which one css file is loaded last?

Haroon
  • 615
  • 2
  • 7
  • 12
  • 1
    It might help if you didn't think of this as "defining a class". You are writing rule-sets with selectors that match elements. (These particular selectors match elements based on their class). Then the cascade applies: http://www.w3.org/TR/CSS21/cascade.html#cascade – Quentin Mar 10 '10 at 13:50
  • 1
    If you don't have control over the order of the files in the HTML, you can always make sure one rule wins with the !important flag. – Tom Mar 10 '10 at 13:59

1 Answers1

64

The one loaded last (or as David points out, more accurately included last) wins in this case. Note that it's per-property though, if you load 2 definitions with different properties, the result will be the combination. If a property is in both the first and second, the last wins on that property.

The only way to ensure which is used last/wins is including the <link> elements in the order you want in the page.

For the property, here's an example:

.class1 { color: red; border: solid 1px blue; padding: 4px; } //First .css
.class1 { color: blue; margin: 2px; } //Second .css

is equivalent to:

.class1 { color: blue; border: solid 1px blue; padding: 4px; margin: 2px; }
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 22
    To be pedantic: It isn't actually the one *loaded* last, it is the one that appears last in the source order. Given asynchronous loading, you could have a short stylesheet at the end of the `head` load before a long one at the start. – Quentin Mar 10 '10 at 13:49
  • @Nick Craver Does this still hold if, for example, there are two entries thus in the same file: .class1 {...} .class1 {...} Will the second one listed win? This can happen when CSS is generated by other programs. – Jonathan Sep 06 '19 at 23:49