Printable web & other
Targeting print media
The
@media
rule can be used to target print media, when the user decides to
print the page. This is useful for hiding elements that are not
relevant to print and adding running headers and folio.
<p>The entire page is only visible on screen. Print to see the hidden text.</p>
<p class="print-only">This text is only visible when printing.</p>
+
.print-only {
display: none;
}
/* Use the `print` media query to target print media */
@media print {
*:not(:has(.print-only)) {display: none;}
.print-only {display: block;}
}
The entire page is only visible on screen. Print to see the hidden text.
This text is only visible when printing.
Respecting user preferences and media features
The
@media
rule can also be used to honor user preferences such as dark mode,
reduced motion, or reduced transparency. Its capabilities extend to
specific media features or information about the user's device, such
as device orientation, hover support, main input type, or aspect
ratio. Here are some useful examples:
-
Dark mode:
@media (prefers-color-scheme: dark) {…} -
Reduced motion:
@media (prefers-reduced-motion: reduce) {…} -
Reduced transparency:
@media (prefers-reduced-transparency: reduce) {…} -
Preferred contrast:
@media (prefers-contrast: more) {…} -
Hover support:
@media (hover: hover) {…} -
Main input type:
@media (pointer: fine) {…} -
Aspect ratio:
@media (min-aspect-ratio: 16/9) {…} -
Device orientation:
@media (orientation: portrait) {…}
Combining media queries
You can combine media queries using the
and
and
or
operators. The
and
operator will only apply the styles if both conditions are met. The
or
operator will apply the styles if either condition is met.
/* Only apply styles above 300px and below 600px */
@media (min-width: 300px) and (max-width: 600px) {
/* Styles */
}