Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a printable webpage using CSS media queries?
We can create a printable webpage and control the styling in the print preview using the CSS @media print media query. This powerful CSS feature allows us to define specific styles that only apply when a user prints the webpage or views the print preview. We can control element visibility, adjust layouts, modify colors, and optimize content specifically for print format.
Syntax
@media print {
/* CSS styles for print version */
selector {
property: value;
}
}
Example 1: Showing Content in Print
In this example, we ensure paragraph content is visible in the print preview by setting visibility to visible
<!DOCTYPE html>
<html lang="en">
<head>
<title>Printable Webpage Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
@media print {
p {
visibility: visible;
color: black;
font-size: 12pt;
}
}
</style>
</head>
<body>
<h3>Creating Printable Webpages</h3>
<p>This paragraph will be visible when you print this page or view the print preview. The text is optimized for print with appropriate font size and color.</p>
</body>
</html>
The webpage displays normally on screen. In print preview, the paragraph text appears in black with 12pt font size, optimized for printing.
Example 2: Hiding Elements from Print
This example demonstrates hiding navigation elements and showing only essential content in print
<!DOCTYPE html>
<html lang="en">
<head>
<title>Print-Optimized Page</title>
<style>
.navigation {
background-color: #333;
color: white;
padding: 10px;
}
.content {
margin: 20px;
line-height: 1.6;
}
@media print {
.navigation {
display: none;
}
.content {
margin: 0;
font-size: 11pt;
}
.print-only {
display: block;
}
}
.print-only {
display: none;
}
</style>
</head>
<body>
<div class="navigation">
<a href="#home">Home</a> | <a href="#about">About</a> | <a href="#contact">Contact</a>
</div>
<div class="content">
<h2>Article Title</h2>
<p>This is the main content that should appear in print. Navigation elements will be hidden, and margins will be reduced for better print layout.</p>
</div>
<div class="print-only">
<p><strong>Printed on:</strong> Visit our website for the latest updates.</p>
</div>
</body>
</html>
On screen: Shows navigation bar and content with normal margins. In print preview: Navigation is hidden, margins are reduced, and a print-only message appears at the bottom.
Conclusion
The @media print query is essential for creating print-friendly webpages. By controlling element visibility, adjusting layouts, and optimizing typography, you can ensure your content looks professional when printed while maintaining the original design for screen viewing.
