views:

24

answers:

2

I have used a tutorial to create a widget for my site.

This widget now needs to be dropped into a complex page with existing CSS rules on important tags like *, body, ul, and li.

Is there a way to drop in this widget (currently a separate page with html, css, and javascript) into my webpage without the webpage applying all of its own CSS on top?

+1  A: 

Is there a way to drop in this widget (currently a separate page with html, css, and javascript) into my webpage without the webpage applying all of its own CSS on top?

The easiest way would be to use an iframe.

If you want an embedded widget, the wisest thing to do is to specify the CSS properties inline in the widget's markup. It's bad practice usually, but is the right thing here.

Check out for example what the Facebook Profile badge (you need to be a Facebook user to see it) looks like:

<!-- Facebook Badge START --><a href="http://www.facebook.com/pekkagaiser" target="_TOP" style="font-family: &quot;lucida grande&quot;,tahoma,verdana,arial,sans-serif; font-size: 11px; font-variant: normal; font-style: normal; font-weight: normal; color: #3B5998; text-decoration: none;" title="Pekka Gaiser">Pekka Gaiser</a><br/><a href="http://www.facebook.com/pekkagaiser" target="_TOP" title="Pekka Gaiser"><img src="http://badge.facebook.com/badge/1238473725.2447.1697336437.png" width="120" height="239" style="border: 0px;" /></a><br/><a href="http://www.facebook.com/badges/" target="_TOP" style="font-family: &quot;lucida grande&quot;,tahoma,verdana,arial,sans-serif; font-size: 11px; font-variant: normal; font-style: normal; font-weight: normal; color: #3B5998; text-decoration: none;" title="Make your own badge!">Create Your Badge</a><!-- Facebook Badge END -->

They are very likely to have done a lot of testing on this, so the CSS properties they set in their code, I would recommend to set in your widget, too.

Pekka
A: 

It can be done with an IFrame, but I wouldn't reccomend that. IFrames are messy and they usually don't work as expected. Some browsers block them, some don't support them at all, and interacting with the page they're in from the IFrame page is really hard.

The most clean way is by wrapping the widget in an extra div with an id like widgetwrapper. Then prefix every css rule with #widgetwrapper [space]. That way, the css from the widget won't affect the rest of the page. Make sure you put the css for the widget last in the css. If there's still page rules messing with your widget, overwrite them in the widget css.

Jouke van der Maas
This will often cause problems when rules from the parent page interfere with the widget. This is why most providers of widgets that get spread "in the wild" serve their style rules as inline CSS.
Pekka
See the last sentence. By the way, even with inline styles, the parent css can still mess things up if you don't specify _every_ css property there is inline.
Jouke van der Maas