adding-css-to-iframe
CSS Javascript Web Development

How to Apply CSS to iFrame

iFrame is a very convenient way to display an external content on your webpage. However, it’s little bit complicate if you want to add additional or alter the existing CSS style. You cannot simply add CSS on the parent/wrapper page. In this tutorial, we’ll show you how to use JavaScript to inject CSS into iFrame.

In the snippet below, once everything was loaded, we’ll get the iFrame element by ID. Then get the contentDocument and inject our styles into iFrame using innerHTML.

window.onload = function() {
   let myiFrame = document.getElementById("myiFrame");
   let doc = myiFrame.contentDocument;
   doc.body.innerHTML = doc.body.innerHTML + '<style>/******* Put your styles here *******</style>';
}

Or you can do it with jQuery.

$("#myiFrame").on("load", function() {
  let head = $("#myiFrame").contents().find("head");
  let css = '<style>/********* Put your styles here **********</style>';
  $(head).append(css);
});

Example

For example, here is the 3D CSS Progressbar tutorial page that we want to add to ours using iframe.

<iframe id="myiFrame" width="1024px" height="768px" src="http://127.0.0.1:5501/bar"></iframe>

How to add css to iframe

Suppose that we want to change the length of the progress bar to 45%. Unfortunately, we can’t do something like this from our parent CSS.

.bar {
   width: 45%; /* This will not work */
}

Let’s try using JavaScript. It’s important that you’ll need to wait until the iFrame was loaded before you can inject the CSS. In this case, we’ll put the code in onload event listener.

window.onload = function() {
  let frameElement = document.getElementById("myiFrame");
  let doc = frameElement.contentDocument;
  doc.body.innerHTML = doc.body.innerHTML + '<style>.bar {width:45%;}</style>';
}

Here is the result.

add-css-to-iframe-2

Adding CSS File to iFrame

You can add entire CSS file instead of injecting separated styles by creating link and add it to the iframe’s head.

window.onload = function() {
  let link = document.createElement("link");
  link.href = "style.css";      /**** your CSS file ****/ 
  link.rel = "stylesheet"; 
  link.type = "text/css"; 
  frames[0].document.head.appendChild(link); /**** 0 is an index of your iframe ****/ 
}
Note
This method does not work with cross domain content. You’ll need to set appropriate CORS header but it’s not recommended due to security risks.
Written By

Leave a Reply

Your email address will not be published. Required fields are marked *