Media Types in CSS

The Media Type in a media query specifies the category of device for which the styles should apply. The commonly used media types are:
screen:Refers to devices with screens, such as desktops, tablets, and smartphones.
Used for applying styles that are specifically designed for on-screen viewing.
print:Refers to styles applied when the document is being printed.
Helps optimize the appearance of web pages for paper printing by hiding elements like navigation or adjusting fonts and layout.
all:Applies styles to all devices, both screen and print.
Useful for defining fallback styles that apply universally.
Detailed Explanation with Examples
1. screen Media Type
This media type is commonly used for responsive web design to adjust styles for devices with screens.
Example:
/* Default styles for all devices */
body {
font-size: 16px;
background-color: lightgray;
}
/* Styles specifically for screens with a maximum width of 768px (tablets and smaller screens) */
@media screen and (max-width: 768px) {
body {
font-size: 14px;
background-color: white;
}
}
Explanation:
The default style applies to all devices.
When the device has a screen and its width is less than or equal to 768px, the background color changes to white, and the font size becomes smaller.
2. print Media Type
This media type is used to prepare a webpage for printing, such as hiding unnecessary elements or changing colors to grayscale.
Example:
/* Default styles */
body {
font-size: 16px;
background-color: white;
color: black;
}
nav, footer {
display: block;
}
/* Styles for print */
@media print {
body {
font-size: 12px;
color: black;
background-color: none;
}
nav, footer {
display: none; /* Hide navigation and footer in print */
}
}
Explanation:
The default style is for on-screen viewing.
When printing, the
@media printblock ensures unnecessary elements like the navigation bar and footer are hidden, and colors are adjusted for readability.
3. all Media Type
This media type is used when styles are meant for both screen and print.
Example:
/* Fallback styles for all media types */
@media all {
body {
font-family: Arial, sans-serif;
margin: 0;
}
}
Explanation:
- The
allmedia type ensures a consistent font family and removes margins across all devices and outputs, whether viewed on-screen or printed.
Use Cases for Media Types
screen: Creating responsive designs for mobile, tablet, and desktop.print: Optimizing pages for printing, such as generating PDF-friendly versions.all: Providing baseline styles that work universally across all media types.

