291

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?

  • 1
    Possible duplicate of [How to apply CSS to iframe?](http://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe) – Alexander O'Mara Mar 01 '16 at 22:17
  • More info about **CORS**: https://wikipedia.org/wiki/Content_Security_Policy and https://developer.mozilla.org/docs/Web/HTTP/CORS – ashleedawg Feb 16 '20 at 23:56

13 Answers13

128

You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.

Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.

I use the Prototype framework to make it easier:

frame1.$('mydiv').style.border = '1px solid #000000'

or

frame1.$('mydiv').addClassName('withborder')
ascx
  • 473
  • 2
  • 13
Diodeus - James MacFarlane
  • 107,156
  • 31
  • 147
  • 171
116

In short no.

You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.

codename-
  • 12,008
  • 2
  • 24
  • 29
mmattax
  • 25,441
  • 39
  • 110
  • 143
  • 65
    This is true but don't really help people give an example to of how to – Simon Dragsbæk Sep 27 '13 at 14:24
  • is this just come up in 2018? I remember that I used to config the style of iframe come from outside. I tried to apply css to iframe that rendered by script but it stil not work.l – Võ Minh Feb 08 '19 at 09:57
49

Yes. Take a look at this other thread for details: How to apply CSS to iframe?

var cssLink = document.createElement("link");
cssLink.href = "style.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css";  
frames['frame1'].document.body.appendChild(cssLink); 
Community
  • 1
  • 1
13

You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.

$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")

$("#iframe-id").contents().find("img").addClass("fancy-zoom")

$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });

Good Luck!

ASGM
  • 9,243
  • 25
  • 46
Riyaz Hameed
  • 897
  • 9
  • 10
  • 13
    doesn't work: Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://HOST" from accessing a cross-origin frame. – tubbo Feb 07 '17 at 19:10
  • @tubbo, in your case, you cannot embed unauthorised sites prevented from XSS. This is only for those looking for their own problems, not hackers :p – Riyaz Hameed Jul 16 '19 at 10:43
11

The quick answer is: No, sorry.

It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

Justin Lucente
  • 1,111
  • 1
  • 8
  • 9
8

Use Jquery and wait till the source is loaded, This is how I have achieved(Used angular interval, you can use javascript setInterval method):

var addCssToIframe = function() {
    if ($('#myIframe').contents().find("head") != undefined) {
        $('#myIframe')
                .contents()
                .find("head")
                .append(
                        '<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
        $interval.cancel(addCssInterval);
    }
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);
Priyank Gupta
  • 663
  • 2
  • 6
  • 10
5

Apparently it can be done via jQuery:

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

https://stackoverflow.com/a/13959836/1625795

Community
  • 1
  • 1
adamj
  • 4,049
  • 5
  • 41
  • 58
  • 4
    You can't use this anymore because of the same origin policy in Chrome browser. The error message: `Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin **** from accessing a cross-origin frame.` – Mohammad AlBanna Jun 13 '17 at 20:48
  • @adamj, Can we change overwrite style sheet of iframe element? if yes, kindly add script. – Muhammad Bilal Jul 23 '18 at 07:59
  • this is an excellent answer if you are NOT using content from another webpage outside of your domain but is perfect if you are dealing with content related to your own page. Like rendering image uploads into iframes and such this is an excellent solution. Thank you @adamj – d0rf47 Jan 15 '21 at 19:18
4

Combining the different solutions, this is what worked for me.

$(document).ready(function () {
    $('iframe').on('load', function() {
        $("iframe").contents().find("#back-link").css("display", "none");
    }); 
});
Rami Alloush
  • 1,186
  • 2
  • 11
  • 21
3

A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.

var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary
Cole Busby
  • 382
  • 5
  • 17
  • 1
    this is potentially very problematic since you have no possible way of ensuring that your timeout will be the correct value. I was attempting the same implementation and opted to use the above poster solution since it can be triggered directly by the iframes content onload event. See adamj's answer – d0rf47 Jan 15 '21 at 19:19
3

probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.

Al W
  • 7,008
  • 1
  • 17
  • 39
  • Can you possibly give an example of how this can be done? Do you mean something like ` – Ant May 06 '11 at 20:33
1

Just add this and all works well:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
gnat
  • 6,199
  • 101
  • 49
  • 71
Wahab Ahmed
  • 55
  • 1
  • 10
  • not sure whether this is the correct answer to the given question, but it was a great solution to resize the google form to the width of the device, many thanks! – shiftyscales May 26 '20 at 22:11
  • @shiftyscales I have tried in one of the application and it works perfect – Wahab Ahmed Sep 26 '20 at 19:41
0

Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.

References:

Community
  • 1
  • 1
0

Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine. The only solution is to fetch the page from the server side code and change the needed CSS.

Chdid
  • 260
  • 3
  • 7
  • 2
    This answer is correct in its' content but relates to JavaScript whereas the question relates to CSS. The answer may be that you need to use JavaScript but you don't say that. The answer also assumes that the content in the iFrame is from a different domain, which is not always the case. Lastly, the exact message will vary from browser to browser. – pwdst Jul 22 '15 at 14:08