Send section / DIV to print on printer instead of the whole page
I was searching for a way to print a div using JavaScript on StackOverflow - there were many results esp using jQuery using plugins. But this CSS-only way is really an elegant solution. Worthy of posting it here. Credits at the bottom.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<style type="text/css">
@media print
{
body *
{
visibility: hidden;
}
#section-to-print, #section-to-print *
{
visibility: visible;
}
#section-to-print
{
position: absolute;
left: 0;
top: 0;
}
}
</style>
</head>
<body>
<div id="container">
<header>This is the header</header>
<h1>Title of the Page</h1>
<div id="section-to-print" style="border:1px solid black;width:1200px;margin:0 auto;padding:5px 20px">
DIV / Section to print-only.
</div>
<button onclick="window.print()">Print This Page</button>
<footer>This is the footer</footer>
</div>
</body>
</html>
When in print mode (media query print), the entire body is hidden and at the same time, next, the div to be printed is visible and positioned to top:left.
CTRL+P also works. StackOverflow
About the author
- I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in
Comments
Join the discussionNo comments yet. Be the first to comment.





