How to Apply CSS to Iframe

edit css of elements within iframe

[...] Obviously when the webpage renders that iframe it is calling an html doc hosted somewhere. I need to know if there is a way to alter that css.

The question of how to style an element inside an iFrame has come up on StackOverflow many times before - try having a look here:

How to apply CSS to iframe?

Another post that addresses it can be seen here:

Using CSS to affect div style inside iframe

And one with a rather short explanation here:

CSS override body style for content in iframe?

Add CSS to iframe elements using the page .css file

Styles from the parent will not be applied to the document within the iframe. The best solution is to add the stylesheet to the document in the iframe. Either via javascript or creating a template page to load in via src.

Something like:

  var head = doc.head
var link = doc.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = ...src...
head.appendChild(link)

in your existing javascript.

I've put together a small example with a style block here

Override body style for content in an iframe

An iframe is a 'hole' in your page that displays another web page inside of it. The contents of the iframe is not in any shape or form part of your parent page.

As others have stated, your options are:

  • give the file that is being loaded in the iframe the necessary CSS
  • if the file in the iframe is from the same domain as your parent, then you can access the DOM of the document in the iframe from the parent.

How to apply css to an iframe

Your js-code is not to bad, but there are some syntax-errors (press F12 to enter the console and to view the errorconsole).
More important is, that you want your element to be a link element and you want to append it to the head of your iframe:

$('document').ready(function() {
var cssLink = document.createElement("style");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames[0].document.head.appendChild(cssLink);
});

How to apply css to iframe content?

You can use jQuery's .content() function to access it.

$('yourIframe').contents().find('#yourItemYouWantToChange').css({
opacity: 0,
color: 'purple'
});

Example

Here's an example showing me applying css to the jQuery logo typically found in the top left of the screen. Mind you, it has to be same domain/ports etc, so that's why my example features jsfiddle in the iframe.

http://jsfiddle.net/pPqGe/



Related Topics



Leave a reply



Submit