Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a specific order for CSS properties?

Tags:

css

For example, if I write:

background-color: black;
color: white;

or

color: white;
background-color: black;

Is there any difference between the two and should I care about order?

like image 219
romani Avatar asked Oct 16 '25 14:10

romani


2 Answers

No. You can write them in any order. In the case of duplicates within the same selector, the last rule wins.

p {
  color:blue;
  color:red;
  color:green; /* Green wins */
}

When dealing with multiple selectors, rules that come later will override earlier rules, unless the earlier selector is more specific.

For example, this code will turn all your paragraphs green:

p { color:red; }
/* ... */
p { color:green; }

While this code will turn all your paragraphs red, because the first selector is more specific.

body p { color:red; }
/* ... */
p { color:green; }

While the order of rules within a selector may not matter, I would take care to write them in a predictable order (position rules before sizing rules before colouring rules, for example) simply to make your CSS consistent and slightly more pleasant to maintain.

like image 117
meagar Avatar answered Oct 18 '25 17:10

meagar


In your example there is no difference, however ordering can matter but only in rare instances.

For example, it can sometimes be common to do:

display: block;
display: inline-block;

The parser will always interpret from top to bottom when the styles are in the same rule. In this case inline-block overwrites block because the property is the same name.

However:

ul li{
  font-size: 14px;
}

ul{
  font-size: 12px;
}

In this case, even though the 12px comes after the 14px in the rules, the text in list item elements will be 14px because of the higher precedence of the selector ul li over ul

like image 24
nzifnab Avatar answered Oct 18 '25 16:10

nzifnab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!