Murat Derya Özen
Murat Derya Özen

Reputation: 2154

How to create an isolated DOM Element? One that doesn't inherit css from parents etc

I am providing a widget to my users. They include my JS api in a script tag. Once they have a <div class="PutWidgetHere" /> in their body tag, I aim to render an image and a text box inside the div.

My JS api finds the div with class=PutWidgetHere. It appends an image element and then an input type=text element. The input must be placed right at the center of the image so I use absolute positioning relative to the div, z-index and a couple other css properties.

All in all, I am able to accomplish this fine on a blank page. However, if I integrate my widget on a populated page, say the homepage of StackOverflow, things get ugly. It still works but looks ugly. Mostly because my input text inherits CSS properties from the page such as padding, margin, hover etc.

How can I prevent the page from messing with my widget?

Upon research, I found out that you can't disable inheriting of CSS properties for an element. For padding and margin, I could overwrite them using !important but I cannot do this for all possible CSS properties my input could inherit?

I thought of placing an iframe inside the div. But then this makes it impossible for my image and input elements to talk with the host page. Plus, an iframe (borderless) that hosts an image and a button might mess with the parent page?

Any suggestions on how to isolate my input text from parent CSS is welcome :)

Upvotes: 1

Views: 740

Answers (1)

Anatoliy  Gusarov
Anatoliy Gusarov

Reputation: 808

Get all styles that makes everything ugly and insert them into style property of element, with has highest priority then id and class styles.

Update: You can also add some unique ID to your element and create custom stylesheet. You can either add <style> with html, or load <style> with javascript, or add to tag later after page load.

Update 2 Here is example of styles override http://jsfiddle.net/zhhxC/

Upvotes: 2

Related Questions