How to use the HTML <link> Media Attribute to Load CSS

The HTML <link media> attribute is used to specify which device type an asset (usually a CSS file) should be optimized for. This way you can have different CSS stylesheets for different purposes.

The media attribute takes several values, with the most common ones being:

  • all: is the default, which applies to all media type devices.
  • screen: is for computer screens, tablets, smartphones — any screen.
  • print: is for Print preview mode, and printed pages.

So in practice, you can have different CSS stylesheets that are optimized for screen and print respectively.

For example:

<head>
  <link rel="stylesheet" type="text/css" href="theme.css">
   <link rel="stylesheet" type="text/css" href="screen.css" media="screen">
  <link rel="stylesheet" type="text/css" href="print.css" media="print">
</head>

In the example above:

  • The first <link> element doesn’t specify a media type, which means that it uses the media="all" attribute by default (which applies to all media types). It’s not visible, but it’s there.
  • The second <link> element uses the media="screen" attribute, which means that this stylesheet is optimized for screens.
  • The third <link> element uses the media="print" attribute, which means that this stylesheet is optimized for print/preview.

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on