Media print css Using Javascript
Posted By : Rajan Rawat | 21-Nov-2017
You can print the
Let's take a quick look at how we can write media queries for printable and exportable content. It's super-easy, it'll only take a minute! We'll use this Adobe XD keyboard shortcut cheatsheet from my blog/website as an example.
Now let's see that how it works. we have to write the media query for the printable content and exportable content. The process is very easy, it will take just one minute.
Step 1: Media Queries for Print CSS
Firstly we
@media print {
/* styles here */
}
You can write
Step 2: Redundancy Hiding
whenever a user
- UI elements
- Header/footer
- Sidebar content
- Forms and CTA
So we need to hide these elements while printing the page using the
@media print {
header, footer, aside, form, … {
display: none;
}
}
Step 3: Customization of Page Margins
For defining the page margins and stacking contents please use the cm instead of px.
so
@media print {
header, footer, aside, form, … {
display: none;
}
article {
width:100%!important;
padding:0!important;
margin:0!important;
}
}
@page {
margin: 2cm;
}
Now let's see Full example
<html>
<head>
<style type="text/
@media print {
.noprint { display: none; }
.printme { display: block; }
}
#funk {
width: 50%;
border: solid red 3px;
}
.isblue {
border: solid blue 5px;
background-color: lightblue;
}
#zonk {
width: 40%;
}
</style>
<script type="text/javascript">
function printDiv( byId )
{
var divall = document.getElementsByTagName("div");
for ( var d = 0; d < divall.length; ++d )
{
var div = divall[d];
div.className = div.className.replace("printme","noprint");
}
var div = document.getElementById( byId );
div.className = div.className.replace("noprint","printme");
window.print( );
}
</script>
</head>
<body>
<div id="funk" class="noprint">
<h1>Yowser!</h1><br/>
Want to print me?<br/>
<input type="button" value="Then click here!" onclick="printDiv('funk');"/>
</div>
<div class="noprint">
Stuff that will never get printed!
</div>
<div id="zonk" class="isblue noprint">
<h2>Coupon worth $2 million dollars!<h2>
<br/>
<i>Expires April 1, 1932</i>
<br/>
</div>
<a class="noprint" href="#" onclick="printDiv('zonk'); return false;">PRINT $2,000,000 COUPON</a>
</body>
</html>
OUTPUT
Coupon worth $2 million dollars!
Expires April 1, 1932
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajan Rawat
Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.