Search code examples
csscss-specificity

can I use body two times?


I have a CSS file with some div styles and this CSS has a body, like this:

css1.css

body{
 background-color:#000;
}
#div1{
...
}
#div2{
...
}

in a page I want to use some divs that are in css1.css but with a different body color. So I create another css for this:

css2.css

body{
 background-color:#fff;
}

so in this page I have:

<link rel="stylesheet" type="text/css" href="css1.css">
<link rel="stylesheet" type="text/css" href="css2.css">

css1.css has a body and css2 too, is it right? Can I have any problem doing this?


Solution

  • Yes you can!

    Although you may need to look at css selector specificity: https://developer.tizen.org/dev-guide/web/2.3.0/org.tizen.mobile.web.appprogramming/html/guide/w3c_guide/dom_guide/html_priorities_css.htm. Here is a more illustrated resource:

    enter image description here

    from https://css-tricks.com/specifics-on-css-specificity/

    The specificity depends on the number of tags, ids, classes, pseudo-classes etc that are contained in your selectors. If there is a tie between selectors then the order matters.

    Those two selectors (for body) have the same specificity (=0001) so the second one will override the common properties of the first.

    Or in other words the body background-color will be #fff :). If that is useful to you is a different question.