Role of media attribute on the LINK element

The media attribute on the LINK element specifies the target media or device type for which an external style sheet is intended. This allows you to apply different styles for different output devices like screens, printers, or mobile devices.

Syntax

<link rel="stylesheet" href="stylesheet.css" media="media-type">

Possible Values

Media Type Description
all Suitable for all devices (default)
print Intended for printed material
screen Intended for computer screens
handheld Intended for handheld devices

Example: Print-Specific Styles

The following example links a CSS file specifically for print media −

<!DOCTYPE html>
<html>
<head>
    <title>Media Attribute Example</title>
    <link rel="stylesheet" type="text/css" media="print" href="/css/print-styles.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        .content {
            color: blue;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="content">
        This content will appear blue on screen, but the print stylesheet will override this for printing.
    </div>
</body>
</html>
The page displays blue text on screen. When printed, the external print stylesheet would apply different formatting.

Example: Multiple Media Types

You can specify multiple media types separated by commas −

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Media Types</title>
    <link rel="stylesheet" type="text/css" media="print, handheld" href="/css/mobile-print.css">
    <style>
        .message {
            background-color: lightgreen;
            padding: 15px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="message">
        This stylesheet applies to both print and handheld devices.
    </div>
</body>
</html>
A green box with rounded corners containing the message appears on screen. The external stylesheet would apply to both print and handheld devices.

Conclusion

The media attribute enables you to create device-specific styles by linking different CSS files for different media types. This is essential for responsive design and optimal user experience across various devices.

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

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements