Parent’s styles in an iframe
Here's a JavaScript that let's you style an iframe just like its top parent. The script is basically just a proof of concept I did after talking to a friend about similar problem he has had in the past, so feel free to modify and use if you like it.
So I have a page, called big.html and a stylesheet for this page, called big.css. On the page there is an iframe that loads small.html. small.html has its own style, called small.css. What my little Javascript function does is:
- Getting all top parent's
<link>tags - Looping through the tags and checking if the
relattribute has valuestylesheet - For all stylesheets found, makes a copy of the link tag and all its attributes and adds it to the head of the iframed page
Here's the code:
function styleMe() { if(window.top && window.top.location.href != document.location.href) { // I'm small but I'm not alone // all parent's <link>s var linkrels = window.top.document.getElementsByTagName('link'); // my head var small_head = document.getElementsByTagName('head').item(0); // loop through parent's links for (var i = 0, max = linkrels.length; i < max; i++) { // are they stylesheets if (linkrels[i].rel && linkrels[i].rel == 'stylesheet') { // create new element and copy all attributes var thestyle = document.createElement('link'); var attrib = linkrels[i].attributes; for (var j = 0, attribmax = attrib.length; j < attribmax; j++) { thestyle.setAttribute(attrib[j].nodeName, attrib[j].nodeValue); } // add the newly created element to the head small_head.appendChild(thestyle); } } // maybe, only maybe, here we should remove the kid's own styles... } else { alert('I hate to tell you that, but you are an orphant'); } }
To see the code in action, see big.html.

May 1st, 2007 at 2:00 pm
Brilliant. I’m in the enemy ASP.NET camp, but this worked perfectly for me, too!
I used it to style a custom app within a Sharepoint site, using a Page Viewer Web Part.
Very cool, thanks!
July 15th, 2008 at 8:21 am
Hello,
Here’s a function to style iframes from the parent
/* Function to style child iframes
*
* Arguments:
*
* style_href: link to stylesheet (use absolute links)
*
* src_part: (optional) a partial string from iframes src attribute, if not given all iframes will be styled
*
*/
function styleIframes(style_href, src_part) {
if (!src_part) src_part = “”;
var iframes_array = document.getElementsByTagName(”iframe”);
var styled_iframes_array = new Array;
for(var i = 0; i