CSS Independent Content

From GreaseSpot Wiki
Revision as of 03:07, 3 June 2007 by Henrik (talk | contribs) (Made explanation more to the point.)
Jump to navigationJump to search

Any HTML you inject into a site is subject to the CSS rules of that site. For many modifications, this is what you want: the elements you inject will fit in nicely. But if you inject something – perhaps a configuration panel – that should look the same across an entire site where styles can vary wildly (e.g. MySpace, eBay) or across multiple sites, you may find that you want it exempt from the site CSS.

One solution is to do your stuff in an iframe:

 /* Creates and returns an element by name and sets its attributes from a hash */
 function tag( name, attr ) {
   var node = doc.createElement( name );
   attr = attr || {};
   for( var i in attr )
     node.setAttribute( i, attr[i] );
   return node;

 var css = "position:fixed; left:0; bottom:0; border:0; " +
   "margin:0; padding:0; overflowY:auto; overflowX:hidden";

 var doc = document;
 var iframe = tag( "iframe", { style:css, src:"about:blank" } );
 doc.body.appendChild( iframe );
 var win = unsafeWindow.frames[unsafeWindow.frames.length-1];
 doc = win.document;
 /* add things to doc.body */
 iframe.style.height = (16 + doc.body.offsetHeight) + "px";
 iframe.style.width = (16 + doc.body.offsetWidth) + "px";