By John


2008-10-20 08:27:14 8 Comments

I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?

26 comments

@K.Suthagar 2016-12-29 03:47:08

Here, There are two things inside the domain

  1. iFrame Section
  2. Page Loaded inside the iFrame

So you want to style those two sections as follows,

1. Style for the iFrame Section

It can style using CSS with that respected id or class name. You can just style it in your parent Style sheets also.

<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>

<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>

2. Style the Page Loaded inside the iFrame

This Styles can be loaded from the parent page with the help of Javascript

var cssFile  = document.createElement("link") 
cssFile.rel  = "stylesheet"; 
cssFile.type = "text/css"; 
cssFile.href = "iFramePage.css"; 

then set that CSS file to the respected iFrame section

//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile); 
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);

Here, You can edit the Head Part of the Page inside the iFrame using this way also

var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
   $("<link/>",{ 
      rel: "stylesheet", 
      href: urlPath, 
      type: "text/css" }
     ));

@Tamas Czinege 2008-10-20 09:07:48

Edit: This does not work cross domain unless the appropriate CORS header is set.

There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

<iframe name="iframe1" id="iframe1" src="empty.htm" 
        frameborder="0" border="0" cellspacing="0"
        style="border-style: none;width: 100%; height: 120px;"></iframe>

The style of the page embedded in the iframe must be either set by including it in the child page:

<link type="text/css" rel="Stylesheet" href="Style/simple.css" />

Or it can be loaded from the parent page with Javascript:

var cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);

@Rehno Lindeque 2011-02-02 19:54:24

Please note, it seems to me like some of the examples posted before are now invalid for html5. You can access the frame's contents as follows: document.getElementById("myframe").contentDocument. Embedding the css still doesn't seem to work for me though.

@Knu 2011-05-23 19:05:15

link may only appear in the HEAD

@mojuba 2011-09-26 12:47:09

Worked for me only when I did ...document.head.appendChild(cssLink) - Firefox and Safari.

@Simon East 2011-11-04 00:52:53

Does this actually work cross-domain? I don't think it would.

@Kevin 2011-11-27 17:37:41

Just so no1 else has to test it to find out: correct, it doesn't work cross-domain. Immediately upon doing frames['name'] you get "Unsafe JavaScript attempt to access frame with URL blah from frame with URL blah. Domains, protocols and ports must match."

@podperson 2013-09-05 16:15:06

Does not work for IE8 as far as I can tell (whether added to body or head).

@kikito 2014-03-23 16:53:32

This might be a stupid question, but woldn't using inline CSS instead of the href attribute bypass the cross-domain issue?

@kikito 2014-03-23 16:57:14

I answer myself: no, since the error happens "immediately upon doing frames['name']".

@Daniel Cheung 2014-11-02 04:48:17

such hack though, never thought anyone would figure out an answer. good job!

@pmont 2014-11-21 20:55:19

Update from late 2014... This doesn't seem to work with Chrome 38. The CSS is getting loaded into the head but no styles. Also manually inserting the <link> element into the body doesn't bring in the styles either. Wonder if it's a Chrome security thing.

@Manik Arora 2014-12-16 11:05:44

I haven't tried it but this might work if we use the absolute url of CSS file appended by javascript in the iframe something like- example.com/css/style.css

@vineet 2015-09-09 11:40:23

it show error i.e, TypeError: frames.frame1 is undefined

@César León 2016-09-23 14:24:01

In my case it shows this error: frames.frame1.document is undefined

@SequenceDigitale.com 2012-09-20 22:21:17

I met this issue with Google Calendar. I wanted to style it on a darker background and change font.

Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents it is possible to get the entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php, which will contain the original content with modifications:

$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');

Adding the path to your stylesheet:

$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);

(This will place your stylesheet last just before the head end tag.)

Specify the base url form the original url in case css and js are called relatively:

$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);

The final google.php file should look like this:

<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;

Then you change the iframe embed code to:

<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>

Good luck!

@Artsen 2014-07-26 22:56:38

First off, I want to say that this is a great solution, however it doesn't always work. If you try it with youtube it will just forever buffer. Any ideas why?

@Chris Houghton 2014-08-11 16:13:35

FYI, this is basically hacking.

@SequenceDigitale.com 2014-08-12 16:58:52

You can call that hacking by definition if you want. But you didn't offer any better solution... This solution is not a way to dammage Google service or to trick people in a way to exploit their weakness.

@deweydb 2014-08-19 23:52:51

I would kill for a way to make this solution work with google docs. Its throwing all sorts of javascript errors. "Uncaught TypeError: Cannot read property 'a' of undefined "

@deweydb 2014-08-20 01:12:15

Nevermind, i figured it out, posted the solution here: stackoverflow.com/questions/25395279/…

@alastair 2015-02-05 16:31:01

@ChrisHoughton FYI, it basically isn't. It might, however, render the entire iframe pointless (one reason for using iframes, for instance, is for security purposes, e.g. with card payments, and if you do what is suggested here you'll probably cause yourself problems).

@Daniel Dewhurst 2015-07-23 15:27:21

This will only work for completely static content, for example anything dynamic like a form won't work.

@Basic 2015-10-13 23:28:22

Also worth noting that you won't be sending the correct cookies any more...

@Avishay28 2016-05-04 08:22:48

In my case, file_get_contents() doesn't grab the <head> section, any idea why?

@bdsl 2017-01-10 15:10:36

By doing this you are always getting the calendar as a non-logged in user. With the normal html iframe the user would see their own personal calendar if they were logged into google, but since your PHP code can't know the users Google session ID it can't fetch their personal calendar.

@TecBrat 2017-01-13 16:07:19

If the TOS allows it, and a developer were determined enough, they could probably use CURL to do this, and make everything work. IFRAME not needed. (TOS of most services will not allow this).

@MNKY 2018-05-05 05:47:29

I don't think you can do this anymore (2018)

@Phil Tune 2018-05-11 18:07:17

Have had to do similar things with Oracle Taleo to override their interface and inject CSS. When you're doing things for clients, you gotta do what you gotta do.

@Ajay Malhotra 2017-09-01 10:15:49

use can try this:

$('iframe').load( function() {
     $('iframe').contents().find("head")
     .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
  });

@Mr. Anderson 2017-11-09 13:14:09

If your iframe comes from different origin, the CORS mechanism will not allow this workarround.

@adrhc 2018-10-25 20:35:16

What if the iframe-url is CORS enabled for all locations?

@Rami Sarieddine 2012-11-21 16:17:35

var $head = $("#eFormIFrame").contents().find("head");

$head.append($("<link/>", {
    rel: "stylesheet",
    href: url,
    type: "text/css"
}));

@Rami Sarieddine 2014-08-22 13:49:57

@deweydb i used it with a cross domain iframe specifically. but I can only beg your forgiveness!

@deweydb 2014-08-22 20:56:49

@ramie and you tested that in multiple browsers? most browsers are throwing a security error.

@J.Tural 2015-12-24 09:24:20

I saw this idea before but add a link to file its really great and professional ... +up

@David Bradshaw 2013-06-24 11:14:10

Expanding on the above jQuery solution to cope with any delays in loading the frame contents.

$('iframe').each(function(){
    function injectCSS(){
        $iframe.contents().find('head').append(
            $('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
        );
    }

    var $iframe = $(this);
    $iframe.on('load', injectCSS);
    injectCSS();
});

@h.coates 2014-07-07 07:34:38

The '$this' is need to be a '$(this)' for it to work. Nice when it does :)

@James Yang 2017-01-04 02:27:00

As an alternative, you can use CSS-in-JS technology, like below lib:

https://github.com/cssobj/cssobj

It can inject JS object as CSS to iframe, dynamically

@Jeeva 2016-10-28 03:14:28

var link1 = document.createElement('link');
    link1.type = 'text/css';
    link1.rel = 'stylesheet';
    link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);

@Kirankumar Dafda 2016-12-03 09:12:09

I have checked this answer many times what is richTextField here ?

@Jeeva 2016-12-03 10:35:22

it's the iframe name

@Kirankumar Dafda 2016-12-05 05:04:06

Is this working for cross domain links too ?

@Jeeva 2016-12-05 22:15:40

I didn't tried, but I guess It won't because its against the sandbox

@T.Todua 2016-10-17 08:01:32

The best way may be the following (if you control target site):

1) set the iframe link with style parameter, like:

http://your_site.com/target.php?style=a%7Bcolor%3Ared%7D

(the last phrase is a{color:red} encoded by urlencode function.

2) set the receiver page target.php like this:

<head>
..........
<style><? echo urldecode($_GET['style']);?> </style>
..........

@Kano 2018-08-21 12:16:44

Warning: this is injection at its finest.

@karlisup 2016-10-03 19:41:01

There is a wonderful script that replaces a node with an iframe version of itself. CodePen Demo

enter image description here

Usage Examples:

// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);

// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
  return iframify(component, {});
});

// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
  headExtra: '<style>.component { color: red; }</style>',
  metaViewport: '<meta name="viewport" content="width=device-width">'
});

@Dylan Watson 2018-11-07 23:59:38

Why would you want to do that?!

@jtheletter 2016-07-07 00:59:53

Other answers here seem to use jQuery and CSS links.

This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  '.some-class-name {' +
  '  some-style-name: some-value;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

@CodeRows 2016-05-19 20:20:18

Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things

this works even if iframe is loading a different domain

check about postMessage()

plan is, send the css to iframe as a message like

iframenode.postMessage('h2{color:red;}','*');

* is to send this message irrespective of what domain it is in iframe

and receive the message in iframe and add the received message(CSS) to that document head.

code to add in iframe page

window.addEventListener('message',function(e){

    if(e.data == 'send_user_details')
    document.head.appendChild('<style>'+e.data+'</style>');

});

@JannuD 2010-12-08 09:46:02

Well, I have followed these steps:

  1. Div with a class to hold iframe
  2. Add iframe to the div.
  3. In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }

This works in IE 6. Should work in other browsers, do check!

@MSD 2011-03-07 18:12:51

need to control div inside of iframe, this does not

@Zbigniew Wiadro 2013-03-21 09:07:13

My compact version:

<script type="text/javascript">
$(window).load(function () {
    var frame = $('iframe').get(0);
    if (frame != null) {
        var frmHead = $(frame).contents().find('head');
        if (frmHead != null) {
            frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
            //frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
        }
    }   
});
</script>

However, sometimes the iframe is not ready on window loaded, so there is a need of using a timer.

Ready-to-use code (with timer):

<script type="text/javascript">
var frameListener;
$(window).load(function () {
    frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
    var frame = $('iframe').get(0);
    if (frame != null) {
        var frmHead = $(frame).contents().find('head');
        if (frmHead != null) {
            clearInterval(frameListener); // stop the listener
            frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
            //frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
        }
    }
}
</script>

...and jQuery link:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>

@Tom Merchant 2009-07-28 22:53:01

The above with a little change works:

var cssLink = document.createElement("link") 
cssLink.href = "pFstylesEditor.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 

//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this

var doc=document.getElementById("edit").contentWindow.document;

//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();

//Then append child
doc.body.appendChild(cssLink);

Works fine with ff3 and ie8 at least

@Tigran 2010-12-10 00:25:22

What's myData and where does it come from

@MSD 2011-03-07 18:09:09

read the comment

@Akash 2016-09-13 06:04:41

@Tigran it is for dynamic data

@jperelli 2015-03-18 14:51:00

I found another solution to put the style in the main html like this

<style id="iframestyle">
    html {
        color: white;
        background: black;
    }
</style>
<style>
    html {
        color: initial;
        background: initial;
    }
    iframe {
        border: none;
    }
</style>

and then in iframe do this (see the js onload)

<iframe  onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>

and in js

<script>
    ifstyle = document.getElementById('iframestyle')
    iframe = top.frames["log"];
</script>

It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a "style" tag in parent window

@Palanikumar 2014-09-02 15:18:10

We can insert style tag into iframe. Posted also here...

<style type="text/css" id="cssID">
.className
{
    background-color: red;
}
</style>

<iframe id="iFrameID"></iframe>

<script type="text/javascript">
    $(function () {
        $("#iFrameID").contents().find("head")[0].appendChild(cssID);
        //Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
    });
</script>

@darylknight 2014-09-26 12:11:27

This doesn't work. Seems to insert the style tag correctly but there's no content inside it and no ID.

@Shkur 2016-10-11 14:14:29

don't work in case of Cross-domain

@Mateusz Winnicki 2014-07-31 12:34:27

I think the easiest way is to add another div, in the same place as the iframe, then

make its z-index bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none on your own div, so the iframe would be working in case you need to click on it ;)

I hope It will help someone ;)

@domih 2013-10-15 22:47:12

Here is how to apply CSS code directly without using <link> to load an extra stylesheet.

var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
          '#banner{display:none}; ' +
          '</style>';
jQuery(head).append(css);

This hides the banner in the iframe page. Thank you for your suggestions!

@jmalais 2013-11-22 19:18:49

Does this need an iframe with the id of iframe?

@Zeb McCorkle 2014-08-13 19:01:14

@jmalais Just replace #iframe with #<id> or even iframe to select all iframes

@David A. French 2017-11-29 04:04:16

This doesn't seem to be working for me. The iframe that I'm trying to edit also doesn't have head directly below it in the dom. So does that mean that I need to access the head inside of the html document or is that something that the jquery find function should be able to do by itself?

@David A. French 2017-11-29 04:14:35

Checked the console and it looks like it's been blocked from accessing the iframe contents due to a domain mismatch. I'm using chrome and hosting my dev environment locally currently.

@sorin 2010-03-02 07:16:41

If you want to reuse CSS and JavaScript from the main page maybe you should consider replacing <IFRAME> with a Ajax loaded content. This is more SEO friendly now when search bots are able to execute JavaScript.

This is jQuery example that includes another html page into your document. This is much more SEO friendly than iframe. In order to be sure that the bots are not indexing the included page just add it to disallow in robots.txt

<html>
  <header>
    <script src="/js/jquery.js" type="text/javascript"></script>
  </header>
  <body>
    <div id='include-from-outside'></div>
    <script type='text/javascript'>
      $('#include-from-outside').load('http://example.com/included.html');
    </script> 
  </body>
</html>

You could also include jQuery directly from Google: http://code.google.com/apis/ajaxlibs/documentation/ - this means optional auto-inclusion of newer versions and some significant speed increase. Also, means that you have to trust them for delivering you just the jQuery ;)

@nickdnk 2016-04-15 12:48:35

One should note that this solution does not work if the content of the page is dynamic in any way.

@peter 2011-05-23 16:22:09

The following worked for me.

var iframe = top.frames[name].document;
var css = '' +
          '<style type="text/css">' +
          'body{margin:0;padding:0;background:transparent}' +
          '</style>';
iframe.open();
iframe.write(css);
iframe.close();

@KingRider 2016-09-19 18:05:50

Error: Uncaught TypeError: Cannot read property 'open' of undefined

@parham fazel 2010-11-08 06:25:23

When you say "doc.open()" it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:

doc.open();

doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');

doc.close();

@PageCandy 2009-03-31 21:36:42

You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.

@Lathan 2010-10-12 14:19:21

Careful when you say that something cannot be done, when in reality it is just difficult

@hangy 2008-10-20 08:37:01

An iframe is universally handled like a different HTML page by most browsers. If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.

@A Child of God 2018-01-17 17:45:50

@hangry but... how?

@Horst Gutmann 2008-10-20 08:58:47

If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

Note that depending on what browser you use this might only work on pages served from the same domain.

@ConroyP 2008-10-20 09:00:06

Might be worth noting that the same origin policy will stop this working if the page is on a different domain.

@Protector one 2016-09-26 12:35:37

In the same line of thinking but more succinct: <iframe onload="this.contentDocument.body.style.overflow='hidden';" />

@Ash 2008-10-20 08:52:14

If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.

Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.

This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.

Related Questions

Sponsored Content

100 Answered Questions

[SOLVED] How to horizontally center a <div>?

34 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

31 Answered Questions

[SOLVED] Is there a CSS parent selector?

  • 2009-06-18 19:59:36
  • jcuenod
  • 1716226 View
  • 2865 Score
  • 31 Answer
  • Tags:   css css-selectors

38 Answered Questions

[SOLVED] How do I vertically center text with CSS?

25 Answered Questions

[SOLVED] How to align content of a div to the bottom?

40 Answered Questions

[SOLVED] How to disable text selection highlighting?

30 Answered Questions

[SOLVED] Convert HTML + CSS to PDF with PHP?

26 Answered Questions

[SOLVED] Set cellpadding and cellspacing in CSS?

21 Answered Questions

[SOLVED] How to write a:hover in inline CSS?

19 Answered Questions

[SOLVED] Is it possible to apply CSS to half of a character?

Sponsored Content