Use a new CSS file to override current website's CSS

前端 未结 12 888
梦如初夏
梦如初夏 2020-11-30 10:04

My website has currently 3 CSS files that are automatically included as a part of the website and I do not have access to the source i.e. index.html

12条回答
  •  长情又很酷
    2020-11-30 10:38

    An alternative: Rely on the cascade, instead of specificity

    A number of solutions here recommend using @import to include your css4.css file and then modifying the selectors therein to have a greater specificity or to use the !important declaration, but there is yet another way.

    Paste the entire contents of css4.css at the end of css3.css. In this way, you need not rely on !important or specificity, because the cascading inheritance will adopt your rules at the end of the file if they are of equal specificity.

    With this method, you are sacrificing modularity for easier implementation.

    Example of pasting, relying on cascade:

    /* Contents of css3.css */
    .mycooldiv {
        font: bold 1.2em sans-serif;
        color: tomato;
    }
    
    /* Pasted contents of css4.css */
    .mycooldiv {
        color: lime;
    }
    Hello World

    However, it would be easy enough to create greater specificity by simply prepending html to the beginning of every rule in css4.css, if you don't want to paste it at the end of css3.css. This is preferred to adding !important where it works.

    Example of importing, relying on greater specificity:

    /* @import of css4.css with greater specificity */
    html .mycooldiv {
        color: lime;
    }
    
    /* Contents of css3.css */
    .mycooldiv {
        font: bold 1.2em sans-serif;
        color: tomato;
    }
    Hello World

提交回复
热议问题