How to use CSS media queries to create a printable web page

How to Use CSS Media Queries to Create a Printable Web Page

We can create a printable web page and use the @media print CSS media query to control the styles displayed in the print preview. @media print is a CSS media query that allows us to add page styles to the print preview of any web page. Using it, we can create a printable web page by specifying the visibility of an HTML element to be “visible” or “hidden.” We can also add any other styles we want to use in the print preview screen within the @media print query.

Syntax

@media print { 
/* CSS Styles here */ 
} 

Here, @media print is the CSS media query that we will use to style our print preview page.

Example 1

In this example, we will display the contents of the “p” tag in the print preview of a webpage by setting “visibility” to “visible” in the @media print CSS query.


<html lang="en"> 
<head> 
<title>How to create printable webpage using CSS media queries?</title> 
<style> 
@media print { 
p { 
visibility: visible; 
} 
} </style> 
</head> 
<body> 
<h3>How to create printable webpage using CSS media queries?</h3> 
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil et rem quasi, iusto expedita modi saepe libero voluptatum. 
</body> 
</html 

Example 2

In this example, we will hide the contents of the “p” tag in the print preview of a web page by setting the “visibility” to “hidden” in the @media print CSS query.

<html lang="en"> 
<head> 
<title>How to create printable webpage using CSS media queries?</title> 
<style> 
@media print { 
p { 
visibility: hidden; 
} 
} 
</style> 
</head> 
<body> 
<h3>How to create printable webpage using CSS media queries?</h3> 
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil et rem quasi, iusto expedita modi saepe libero voluptatum. laudantium!</p> 
</body> 
</html> 

Summary

In this article, we learned about the @media print CSS media query and used it to create a printable web page with the help of two different examples. In the first example, we displayed the contents of the “p” tag in the print preview, while in the second example, we hid the contents of the “p” tag in the print preview.

Leave a Reply

Your email address will not be published. Required fields are marked *