DEV Community

Cover image for How to change the webpage CSS styles when the user prints the webpage?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to change the webpage CSS styles when the user prints the webpage?

Originally posted here!

To change the CSS styles of a webpage when the user wants to print the page, you can use the media query syntax of @media followed by the keyword print. The keyword print in this case is the media type.

TL;DR

<html>
  <body>
    <p>Hello World</p>
  </body>

  <!-- CSS styles for the body and the paragrapgh tags -->
  <!-- 
    Using the `@media` syntax and the defining
    a type of `print` to change the styles when
    users want to print the webpage.
  -->
  <style>
    body {
      background-color: white;
    }

    p {
      color: red;
    }

    @media print {
      body {
        background-color: black;
      }

      p {
        color: white;
      }
    }
  </style>
</html>
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a simple HTML showing a paragraph of Hello World like this,

<html>
  <body>
    <p>Hello World</p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now let's change the background color of the body to white and the color of the paragraph element to red color using the style tag (We are using the style tag inside the HTML for simplicity, you can use an external stylesheet too).

<html>
  <body>
    <p>Hello World</p>
  </body>

  <!-- CSS styles for the body and the paragraph tags -->
  <style>
    body {
      background-color: white;
    }

    p {
      color: red;
    }
  </style>
</html>
Enter fullscreen mode Exit fullscreen mode

Now the output of the above HTML code looks like this,

Hello World text shown in red color on the screen

We aim to change the background color of the body tag to black and the paragraph tag to white when the user wants to print the webpage.

To do that we can use the media query syntax of @media followed by the keyword print to set the media type.

It can be done like this,

<html>
  <body>
    <p>Hello World</p>
  </body>

  <!-- CSS styles for the body and the paragrapgh tags -->
  <!-- 
    Using the `@media` syntax and the defining
    a type of `print` to change the styles when
    users want to print the webpage.
  -->
  <style>
    body {
      background-color: white;
    }

    p {
      color: red;
    }

    @media print {
      body {
        background-color: black;
      }

      p {
        color: white;
      }
    }
  </style>
</html>
Enter fullscreen mode Exit fullscreen mode

Now when the user opts to print the web page, the body will be black and the paragraph text will be white.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)