Search code examples
cssstylesheetoverwrite

How do I overwrite certain conditions when you have two CSS files?


I have a page called index.html and about.html. I have a css file called main.css (it's used on every single page because of common css styles) and another called about.css (it holds styles unique to about.html).

On main.css I have this css block:

html, body, form {
    margin: 0px;
    padding: 0px;
    height: 100%;
}

This is creating issues on about.html. In about.css, what can I do so that the html, body, form on that page doesn't use margin: 0px;, padding: 0px;, and height: 100%?

Question:

Essentially, how do I prevent html, body, form { margin: 0px; padding: 0px; height: 100%; } from showing up on about.html? What values can I use so that margin, padding, and height essentially don't exist on about.html


Solution

  • There are a couple things at play here. One, CSS is cascading - meaning if a style exists after another style with the same selectors, the latter will take precedence. If you load a stylesheet after your main.css in the DOM, any styles with the same selectors (exactly as they are in the main.css) will overwrite each other:

    <link href="blah/main.css" ... />
    <link href="blah/overwrite.css" ... />
    

    Second, there is the problem of specificity. Say you have the same element targeted like so:

    .main .last .element { //css }
    .main .element { //css }
    

    Even though the second set of styles are after the first, the first will take precedence because it targets the element more specifically.

    The !important modifier is really only for global changes, which is why people tell you to use it with caution - because if EVERYTHING is !important, nothing is.

    In your specific case:

    Try adding a class on the about us page html element like so:

    <html class="about-us">
    

    And then target the about us page in your main.css file like so:

    html.about-us,
    body.about-us,
    form.about-us { margin: auto; padding: auto; height: auto; }
    

    This takes advantage of the specificity of your selector and overwrites the styles.