-2

I'm building an html preview tool inside a small project and I'm trying to find the best way to place html and the css that will style that html inside an iframe.

I'm able to create the iframe and place the html contents of my div inside. So far that seems to be working correctly in this fiddle

$(function() {

    var $html = $("#html").html();
    var $frame = $('<iframe>');
        $('body').html( $frame );

    var doc = $frame[0].contentWindow.document;
    var $framehtml = $('html',doc);
        $framehtml.html($html);

});

But how do I add css to the head of that iframe? For example, adding the class .mobile you see in the fiddle to the head of the iframe so the image is hidden when the iframe reaches a width of 500px?

EDIT: I don't want to inject a css style sheet. I'd rather create a tag in the head and place the css you see in the fiddle.

cgrouge
  • 177
  • 15
  • Possible duplicate of [Add CSS to iFrame](https://stackoverflow.com/questions/6960406/add-css-to-iframe) – APAD1 Jun 06 '17 at 16:09
  • Possible duplicate of [How to apply CSS to iframe?](https://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe) – Nope Jun 06 '17 at 16:10

1 Answers1

0

@FRAN and @APAD1 were right, this is a duplicate. I was able to use those answers to create my own with this updated fiddle

    var $head = $("#myframe").contents().find("head");                
    $head.append($("<style/>", 
                   {type: "text/css" }));


    var $style = $("#myframe").contents().find("style");                
    $style.append($css);
cgrouge
  • 177
  • 15