Media

The HTML media attribute specifies the target media or device type for which a linked resource, such as a stylesheet, is optimized.

Media Attribute

The media attribute in HTML is used with elements like <link> and <style> to specify the target media for the associated resource, such as whether it should apply to screen displays, print views, or other media types. It helps tailor the presentation of a webpage based on different devices or contexts.

Syntax

index.html
<link rel="stylesheet" href="styles.css" media="screen">

Definition and Usage

The media attribute defines the type of media or device the linked document is intended for.

It is used to indicate that the target URL is optimized for specific devices (like smartphones), print layouts, or speech media.

This attribute can take multiple values.

Applies to

The media attribute can be applied to the following elements:

ElementsAttribute
<a>media
<area>media
<link>media
<source>media
<style>media

Examples

  • A hyperlink using the media attribute:
index.html
<h1>The a media attribute</h1>
<p>
  <a href="att_a_media.asp?output=print" media="print and (resolution:300dpi)">Open media attribute page for print</a>
</p>
  • An image map with an interactive area:
::atter-coords ::
index.html
<img src ="img.jpg" width="145" height="126" alt="Laptop"
usemap="#planetmap">

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>
  • Two separate stylesheets for different media types (screen and print):
index.html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="demo_screen.css">
  <link rel="stylesheet" type="text/css" href="demo_print.css" media="print">
</head>
  <body>
    <h1>Qarpeo Example</h1>
    <p><a href="tryhtml_link_media.htm" target="_blank">Click here</a> to open this page in a new window (without the tryit part).</p>
    <p>If you print this page, or open it in print preview, you will see that it is styled with the media="print" stylesheet. The "print" stylesheet contains black text on white background.</p>
  </body>
</html>
  • Use of the media attribute:
index.html
<h1>The source media attribute</h1>
<picture>
  <source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 465px)" srcset="img_white_flower.jpg">
  <img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;">
</picture>

Conclusion

The media attribute in HTML specifies the target device or media type for which a linked resource (like a stylesheet) is optimized. It allows developers to apply different styles based on the device (screen, print, etc.) or other media conditions. For example, media="print" can be used to define styles for printed pages.