Lee Theobald
Lee Theobald

Reputation: 8587

Protecting Elements From Unspecific CSS

We're currently having to write some widgets that are going to be embedded on various pages. As far as I know, I have two possible options to protect these widgets from loose CSS rules (e.g. a general p { background-color: red } for example). These are:

  1. Using a reset stylesheet to ensure all CSS properties for the widget elements are set to known defaults. Using a CSS preprocessor like Less, this can be simple enough:

    html body #myWidgetID {
      .resetCSSMixin();
    }
    
  2. Embedding the element into an iframe much like suggested on HTML5 Rocks.

Option 1 is a known entity to me. It's not pretty but it'll work. Option 2 I'm not too sure about. Would a large amount of iframes slow the page down? We now a lot of our sites will be visited on old hardware & slow internet speeds. We also need to support old IE 8 - Could there be browser compatibility issues? We certainly can't use the newer iframe attributes.

Can anyone suggest any reasons why I shouldn't go with option 2? It sounds like the nicer option, but I'd like a little more guidance before making the call.

Upvotes: 1

Views: 223

Answers (2)

GolezTrol
GolezTrol

Reputation: 116110

iframes are a very old feature, so IE8 support is not an issue. The main difference is that an iframe loads a separate document into a frame. This will have a couple of effects:

  • The widget is loaded in a separate request. It will need its own HTML page, so you will have an extra HTTP request, and more data that needs to be transferred.
  • Still, initial page load might even be faster, because the page can be displayed before the widget is loaded.
  • An iframe is a boundary. Pages in the iframe cannot modify elements outside of the iframe. This can be an advantage (3rd party banners/widgets that must not have access due to security risks) or a disadvantage (if you want your own widget to have access to the parent).
  • Because it is a separate page, it has its own set of CSS and is not in any way (apart from width/height) affected by the parent page. This can be a advantage or a disadvantage as well. You have complete control of the looks of your widget, but it's hard to give the users/implementors of your widget any possibility to do some additional styling.

Upvotes: 1

Robin like the bird
Robin like the bird

Reputation: 752

If you care about a CSS property, you will style your widget element with that property either using a more specific rule in the stylesheet or in the style DOM attribute. Either way, it will override loose selectors.

If you don't care about a CSS property, there is no point in resetting it, and you should probably allow it to be themed.

Upvotes: 0

Related Questions