Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?
-
1Possible 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
14 Answers
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')

- 473
- 2
- 13

- 112,730
- 33
- 157
- 176
-
3see my this question it's similar http://stackoverflow.com/questions/1962707/how-to-give-style-to-iframed-page-content-using-parent-pages-css but can't we change style if frame is from another server? – Jitendra Vyas Dec 29 '09 at 13:27
-
25That is correct. The Iframe content is subject to the same-domain policy. If it's from your domain, you can control it, if not, you're locked out. This prevents all kinds of Iframe-based page hijacking. – Diodeus - James MacFarlane Dec 29 '09 at 16:08
-
5
-
3
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.
-
79This 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
Yes. Take a look at this other thread for details: How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">

- 4,681
- 3
- 17
- 25

- 784
- 5
- 7
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!

- 11,051
- 1
- 32
- 53

- 1,087
- 12
- 10
-
16doesn'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
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.

- 1,151
- 1
- 8
- 9
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);

- 803
- 2
- 8
- 10
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");
});
});

- 2,308
- 2
- 27
- 33
Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
-
8You 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.` – Mohammed AlBanna Jun 13 '17 at 20:48
-
@adamj, Can we change overwrite style sheet of iframe element? if yes, kindly add script. – Billu Jul 23 '18 at 07:59
-
2this 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
-
-
Mohammed is right, this no longer works due to CORS, but it would work if it's same domain that you are controlling. – adamj Jun 24 '23 at 08:49
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.

- 7,539
- 1
- 19
- 40
-
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@Ant no, for a cross-origin iframe, the embeddable site would need to have the `` tag inside of its own HTML. If the frame's source resides on the same parent domain, then you can inject a style tag (or inline styles) with JavaScript. – kano Jan 28 '22 at 08:18
If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});

- 4,643
- 1
- 41
- 38
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.

- 280
- 3
- 7
-
2This 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
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

- 398
- 6
- 17
-
2this 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
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">

- 6,213
- 108
- 53
- 73

- 159
- 1
- 1
- 11
-
1not 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
-
1@shiftyscales I have tried in one of the application and it works perfect – Wahab Ahmed Sep 26 '20 at 19:41
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:

- 1
- 1

- 15
- 2
-
1The question specifically asks "using CSS only". With that in mind, your answer is wrong. – Serj Sagan Sep 23 '16 at 22:44
-