Open In App

How to hide an element when printing a web page using CSS?

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
1 Likes
Like
Report

Media queries allow you to apply different styles for different media types, such as screens or print. To hide certain elements (like headers or images) when printing a webpage, you can use the @media print query and set the visibility: hidden or display: none to hide those elements during printing.

Below are two examples that demonstrate how to hide elements when printing a web page.

Example 1: Hide an <h1> Element When Printing

In this example, the <h1> element is visible on the screen, but it is hidden when the page is printed by using a media query.

html
<!DOCTYPE html>
<html>

<head>
    <title>Hide element at print</title>
    <style>
        body {
            text-align:center;
        }
        h1 {
            color:green;
        }
        @media print {
           .noprint {
              visibility: hidden;
           }
        }
    </style>
</head>

<body>
    <h1 class="noprint">GeeksforGeeks</h1>

    <p>
        GeeksforGeeks: It is a computer science
        portal for geeks
    </p>

</body>

</html>

Output: 


Example 2: Hide an <img> Element When Printing

In this example, an <img> element is visible on the screen but hidden when printing by using the @media print query and display: none to completely remove it from the print layout.

html
<!DOCTYPE html>
<html>

<head>
    <title>Hide element at printing</title>
    <style>
        body {
            text-align:center;
        }
        h1 {
            color:green;
        }
        @media print {
           img {
              visibility: hidden;
           }
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>

    <p>A computer science portal for geeks</p>

    <img src="gfg.png" alt="image">
    <style>
        .noprint {
            visibility: hidden;
        }
    </style>
</body>

</html>

Output: 


Article Tags :

Explore