Skip to content Skip to sidebar Skip to footer

How To Apply Css To Inner Iframe Element Through Parent Window Css Class?

I have a parent(main) page that has some iframe sections. And I want to apply css style to inner iframe element. When I googling for it, I found many post relate to this topic but

Solution 1:

You can not directly apply styles to the inner IFrame element through parent window CSS class even though its domain is same as parent.

As ,(All the iframe's domain is the same as the parent) ..

Best thing you can do is ,to add your main style sheet to the IFrame using javascript or jquery.

 $(document).ready(function(){
        $('#myIframe').load(function(){
            $('#myIframe')
                    .contents().find("body")
                    .html("test iframe");
            $('#myIframe')
                .contents().find("head")
                .append($('<link rel="stylesheet" type="text/css" href="style.css">')
            );
        });
    });

Solution 2:

If all your CSS is in external files something like this might work in your iframe.

<script>window.onload = function() {
    Array.prototype.forEach.call(window.parent.document.querySelectorAll("link[rel=stylesheet]"), function(link) {
        var newLink = document.createElement("link");
        newLink.rel  = link.rel;
        newLink.href = link.href;
        document.head.appendChild(newLink);
    });
};
</script>

It basically asks the parent for all the stylesheets then adds links to the iframe with the same references. If the iframe and the parent page are not at the same location on your server you'd have to manipulate the href appropriately.

Also the code above probably only works on newer browsers.

Post a Comment for "How To Apply Css To Inner Iframe Element Through Parent Window Css Class?"