How to Use CSS with Different Media Types

See CSS: Tips and Tricks for similar articles.

Styles can be defined for different media. For example, you may want to style a page one way for viewing with a browser and a different way for viewing in print. The media type is defined in the <link> tag for external style sheets and in the <style> tag for embedded style sheets.

If the media is undefined then the style rules will apply to all media. Possible values for media are:

  • all
  • print
  • screen
  • speech

In the following example, we'll create style rules for screen and print using CSS.

  1. Create a style element with the media set to screen:
    
    <style type="text/css" media="screen">
    	.warning {
    		color: #ff0000;
    	}
    	h1.warning {
    		text-decoration: underline;
    	}
    	p.warning {
    		font-weight: bold;
    	}
    		.printDisplay {
    		display: none;
    	}
    </style>
    The text will look like this:Screen Version
  2. Create a style element with the media set to print:
    
    <style type="text/css" media="print">
    .warning {
    		color: #660000;
    	}
    		h1.warning {
    		text-decoration: underline;
    		font-size: 1in;
    	}
    	p.warning {
    		font-weight: bold;
    		font-size: .5in;
    	}
    	.screenDisplay {
    		display: none;
    	}
    </style>
    The text will look like this:Print Version
  3. The final markup will look like this:
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>CSS Media</title>
    <style type="text/css" media="screen">
    	.warning {
    		color: #ff0000;
    	}
    	h1.warning {
    		text-decoration: underline;
    	}
    	p.warning {
    		font-weight: bold;
    	}
    	.printDisplay {
    		display: none;
    	}
    </style>
    <style type="text/css" media="print">
    	.warning {
    		color: #660000;
    	}
    	h1.warning {
    		text-decoration: underline;
    		font-size: 1in;
    	}
    	p.warning {
    		font-weight: bold;
    		font-size: .5in;
    	}
    	.screenDisplay {
    		display: none;
    	}
    </style>
    </head>
    <body>
    <h1 class="warning">WARNING</h1>
    	<p class="warning">Don't go there!</p>
    	<p class="printDisplay">This is the print version.</p>
    	<p class="screenDisplay">This is the screen version.</p>
    </body>
    </html>