Search code examples
cssoperator-precedence

Confused about stylesheet precedence


I have read and learned that internal stylesheets will override external ones. And also, I learned that the stylesheet last to be called will override the previous one.

With that said, when I had unintentionally placed an external stylesheet after my <style> tag, I noticed it overwrote the internal. It would make sense, as the external sheet was called last, but with what I have learned so far about internal CSS as having higher precedence, it shouldn't matter if it was placed before the external one, right?


Solution

  • There are only three types of styles:

    • Inline
    • Embedded
    • External

    And the inline styles are very powerful, because, they are included along with the tag:

    <div style="/* rules */">
    

    The embedded styles are almost similar to external styles. Embedded styles are defined by using the <style> tag inside the same page. The main difference between embedded styles and external are, embedded are specific to the page, which they are contained, while external are generic to any page that uses it.

    <!-- External Style -->
    <link rel="stylesheet" href="style.css" />
    <!-- Embedded Style -->
    <style>
      /* Page Specific */
    </style>
    

    And specificity matters in the way of how you import the styles. Always load your external styles <link /> first and then your page specific embedded <style> tags.

    The specificity is as follows:


    * Image credits CSS Tricks.

    I had unintentionally placed an external stylesheet after my <style> tag, I noticed it overwrote the internal.

    Consider I am using bootstrap library, and Google Fonts. I will load them first, and then override them in my own styles.

    <link rel="stylesheet" href="googlefonts.css" />
    <link rel="stylesheet" href="bootstrap.css" />
    <link rel="stylesheet" href="custom-styles.css" />
    

    There's no difference between having your embedded or internal styles in CSS file or using <style> tag. The order of loading precedence matters.

    A CSS file, say style.css with the following contents:

    * {margin: 0; padding: 0; list-style: none;}
    body {font-family: 'Segoe UI'; font-size: 10pt;}
    

    And having a style tag like this:

    <style>
      * {margin: 0; padding: 0; list-style: none;}
      body {font-family: 'Segoe UI'; font-size: 10pt;}
    </style>
    

    Both of them have no difference in them. The order you load matters very much.