Home >Web Front-end >CSS Tutorial >Can CSS @media print be Used to Print Custom Elements?

Can CSS @media print be Used to Print Custom Elements?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 08:49:021107browse

Can CSS @media print be Used to Print Custom Elements?

Printing Custom Elements with CSS

When faced with the need to create a printer-friendly version of a content-rich page, CSS provides a powerful mechanism through the @media print rule. However, the provided solution raises questions on its feasibility and browser compatibility.

Browser Support for @media print

The @media print rule enjoys support from all major modern browsers, including Chrome, Firefox, Safari, and Edge. This ensures that the print styles can be applied consistently across various platforms.

Hiding and Revealing Elements with CSS

To selectively display elements during printing, you can utilize CSS to hide everything except those marked with a specific class. The following CSS snippet achieves this:

@media print {
  * {
    display: none;
  }
  .printable,
  .printable > * {
    display: block;
  }
}

In this approach, all elements with the "printable" class and their children will be visible during printing, while everything else will be hidden.

Negative Selector and Browser Compatibility

While using the "not" selector to exclude elements appears logical, it may not work as expected in certain browsers. To address this, a complementary approach can be employed:

@media print {
  body *:not(.printable *) {
    display: none;
  }
}

This CSS rule hides all elements within the body, except those descendants of elements with the "printable" class.

Displaying Elements in Browser and Printer

To display certain elements in the browser but hide them on print, you can use the following CSS technique:

@media print {
  .noPrint {
    display: none;
  }
}

@media screen {
  .onlyPrint {
    display: none;
  }
}

This approach allows for the inclusion of elements (e.g., links or logos) that are only relevant for the browser or print output, respectively.

The above is the detailed content of Can CSS @media print be Used to Print Custom Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn