How can I efficiently overwrite CSS with a content script?

后端 未结 2 562
情深已故
情深已故 2021-01-16 07:28

My problem is that I want to overwrite a style of a site. Thing is, there is a way to do this, using the !important sentence, as seen in this example.

H

2条回答
  •  攒了一身酷
    2021-01-16 08:08

    The approach I've found easiest and most effective is to wrap whatever html template you're injecting in a div with a very specific id.

    // Your injected HTML template or section of the website you want to change

    Once you've done this, reset all of the CSS that might affect that section.

    #my-specific-id {
    
      // A comprehensive CSS reset
    
    }
    
    // The rest of your CSS will override the reset above
    

    Here is one such reset: http://html5doctor.com/html-5-reset-stylesheet/

    Note that you probably won't need everything from the CSS Reset, so remove what isn't relevant to take some load off the browser. I can't imagine that you really want to reset figcaption, for example.

    As someone writing an extension, you should care a lot about whether or not your extension ruins the user experience on websites you inject scripts into.

    The approach I've outlined will guarantee that only the sections of the website that you specifically care about are changed.

    You can do this with your own templates (say you wanted to add a weather widget to every page without using an iframe) or with specific parts of the page. You could, for example, wrap all

    elements in a highly specific id that you define.

    Here's an example using Sass from a recent project I've been working on...

    #specific-id-css-ultimate-reset {
    html, button, input, div, p, img, form {
        margin: 0;
        padding: 0;
        border: 0;
        outline: 0;
        font-size: 100%;
        vertical-align: baseline;
        background: transparent;
    }
    
    @import "modules/all";
    @import "components/all";
    @import "popups/all";
    }
    
    

提交回复
热议问题