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

Published October 6, 2022

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>

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>

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>

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

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>

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 😃.


Share on: Facebook Twitter