最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript window.print CSS @media not working - Stack Overflow

programmeradmin3浏览0评论

I have this JS function when user clicks on print button.

<script>
function printDiv()
{
  var printer = window.open('','','width=300,height=300');
    printer.document.open("text/html");
    printer.document.write(document.getElementById('news_contents').innerHTML);

    printer.print();

}
</script>

And I included the CSS as

@media print {

  #news_content { 
     color: #666;
        font-size: 12px;
    font-family: Arial,Helvetica,sans-serif;
  }
}

However when user prints, the CSS did not apply. I checked the HTML header, the CSS script is indeed there. Why is it not working? When user prints from Mac, the image in the content area shrinks and became small. Anyway I can have it exactly the same as the website?

Thanks in advance.

I have this JS function when user clicks on print button.

<script>
function printDiv()
{
  var printer = window.open('','','width=300,height=300');
    printer.document.open("text/html");
    printer.document.write(document.getElementById('news_contents').innerHTML);

    printer.print();

}
</script>

And I included the CSS as

@media print {

  #news_content { 
     color: #666;
        font-size: 12px;
    font-family: Arial,Helvetica,sans-serif;
  }
}

However when user prints, the CSS did not apply. I checked the HTML header, the CSS script is indeed there. Why is it not working? When user prints from Mac, the image in the content area shrinks and became small. Anyway I can have it exactly the same as the website?

Thanks in advance.

Share Improve this question edited Oct 3, 2012 at 14:27 Sylph asked Oct 3, 2012 at 14:21 SylphSylph 1,4954 gold badges27 silver badges36 bronze badges 2
  • hope it helps coding.smashingmagazine./2011/11/24/… – Santiago Rebella Commented Oct 3, 2012 at 15:00
  • Hi @SantiagoRebella thanks for the link. Doesn't seem to have any mistake in my coding, not sure why the CSS isn't applied. – Sylph Commented Oct 4, 2012 at 0:14
Add a ment  | 

2 Answers 2

Reset to default 5

I have the same problem, what I did, was put the:

<style>
   @media print
   { 
     /..../
   }
</style>

Inside the DIV - I believe it's news_contents in your case.
Hope that helps.

I believe you are having a problem because your @media declaration is in the parent window; and you are opening a new window and appending content to it for printing.

Therefore the new document in the new window knows nothing about your @media CSS declaration.

发布评论

评论列表(0)

  1. 暂无评论