Parent’s styles in an iframe

September 3rd, 2006. Tagged: CSS, JavaScript

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:

  1. Getting all top parent's <link> tags
  2. Looping through the tags and checking if the rel attribute has value stylesheet
  3. 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( && != document.location.href) {
  // I'm small but I'm not alone
    // all parent's <link>s
    var linkrels ='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
    // 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.

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov