How to specify the target media within the document language with CSS

CSS media attributes allow you to specify which devices or media types should apply specific styles. This helps create responsive designs that work across different platforms like screens, printers, and handheld devices.

Syntax

/* In CSS */
@media media-type {
    /* CSS rules */
}

/* In HTML link tag */

Common Media Types

Media Type Description
screen Computer screens, tablets, phones
print Printers and print preview
all All media types (default)
speech Screen readers and speech synthesizers

Example: Using Media Attribute in HTML

The following example shows how to link different stylesheets for different media types −

<!DOCTYPE html>
<html>
<head>
    <title>Media Target Example</title>
    <link rel="stylesheet" type="text/css" media="screen" href="/css/screen.css">
    <link rel="stylesheet" type="text/css" media="print" href="/css/print.css">
    <style media="screen">
        .screen-only {
            background-color: #e0f7fa;
            padding: 20px;
            border: 2px solid #00796b;
        }
    </style>
    <style media="print">
        .print-only {
            color: black;
            font-size: 12pt;
        }
        .screen-only {
            display: none;
        }
    </style>
</head>
<body>
    <div class="screen-only">
        <h1>This appears only on screen</h1>
        <p>This content is styled for screen viewing.</p>
    </div>
    <div class="print-only">
        <p>This content is optimized for printing.</p>
    </div>
</body>
</html>
On screen: A light blue box with dark green border containing "This appears only on screen" heading and description text.
On print: Only the print-optimized text appears in black, 12pt font without the colored box.

Example: Multiple Media Types

You can specify multiple media types separated by commas −

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Media Types</title>
    <style media="screen, handheld">
        .multi-media {
            background-color: #fff3e0;
            padding: 15px;
            border-radius: 8px;
            font-family: Arial, sans-serif;
        }
    </style>
</head>
<body>
    <div class="multi-media">
        <h2>Responsive Content</h2>
        <p>This styling applies to both screen and handheld devices.</p>
    </div>
</body>
</html>
A light orange rounded box with Arial font containing "Responsive Content" heading and description text, visible on both screens and handheld devices.

Conclusion

CSS media attributes provide precise control over which devices receive specific styles. Use the media attribute in HTML link tags or CSS @media rules to create device-appropriate designs for better user experience across all platforms.

Updated on: 2026-03-15T11:35:35+05:30

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements