Reset/remove CSS styles for element only

前端 未结 14 851
长情又很酷
长情又很酷 2020-11-22 00:52

I\'m sure this must have been mentioned/asked before but have been searching for an age with no luck, my terminology must be wrong!

I vaguely remember a twee

14条回答
  •  醉话见心
    2020-11-22 01:34

    Let me answer this question thoroughly, because it's been a source of pain for me for several years and very few people really understand the problem and why it's important for it to be solved. If I were at all responsible for the CSS spec I'd be embarrassed, frankly, for having not addressed this in the last decade.

    The Problem

    You need to insert markup into an HTML document, and it needs to look a specific way. Furthermore, you do not own this document, so you cannot change existing style rules. You have no idea what the style sheets could be, or what they may change to.

    Use cases for this are when you are providing a displayable component for unknown 3rd party websites to use. Examples of this would be:

    1. An ad tag
    2. Building a browser extension that inserts content
    3. Any type of widget

    Simplest Fix

    Put everything in an iframe. This has it's own set of limitations:

    1. Cross Domain limitations: Your content will not have access to the original document at all. You cannot overlay content, modify the DOM, etc.
    2. Display Limitations: Your content is locked inside of a rectangle.

    If your content can fit into a box, you can get around problem #1 by having your content write an iframe and explicitly set the content, thus skirting around the issue, since the iframe and document will share the same domain.

    CSS Solution

    I've search far and wide for the solution to this, but there are unfortunately none. The best you can do is explicitly override all possible properties that can be overridden, and override them to what you think their default value should be.

    Even when you override, there is no way to ensure a more targeted CSS rule won't override yours. The best you can do here is to have your override rules target as specifically as possible and hope the parent document doesn't accidentally best it: use an obscure or random ID on your content's parent element, and use !important on all property value definitions.

提交回复
热议问题