How do I hide an element when printing a web page?

In this tutorial, we will learn how to hide an element when printing a web page using CSS. By Shahnail Khan Last updated : July 11, 2023

Digital media has gained popularity over print media. Still, many companies prefer print media to outreach people. Are you one amongst them? Do you also want to print a web page for commercial purposes? At times, it may happen that you don't want a particular section or an element of a web page to be printed out but should be there on your website. In this article, we'll discuss how to hide an element when printing a web page?

How to hide an element when printing a web page?

We'll use a CSS3 module, namely, media query to hide an element when printing web pages. For those of you who aren't familiar with a media query, @media query is a way to make a responsive design. Whenever our screen is resized or we set a particular width of the screen, then a specific CSS property is injected into a page. When printing a webpage, @media print query is used. Inside the @media print query, we have to set visibility to hide to that class from which we want to hide an element.

Example

Let's take an example:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Hiding of an element</title>
   </head>
   
   <style>
      .welc {
      color: blue;
      }
      @media print {
      .description {
      visibility: hidden;
      }
      }
   </style>
   
   <body>
      <div class="IncludeHelp">
         <h1 class="welc">Welcome to IncludeHelp</h1>
         <div class="description">
            <p>Code like pro!!</p>
            <h2>Best website for coders</h2>
         </div>
      </div>
   </body>
</html>

Output (Before printing the web page)

CSS | Hide an elemenet in a webpage (1)

Output (After printing)

CSS | Hide an elemenet in a webpage (2)

In this code, we have set visibility to hidden to the "description" class only in the @media print query. Therefore, the elements inside the description class are hidden when printing the web page.

CSS Examples »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.