How to Use CSS with Different Media Types

  • google plus

In Brief...

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

Take our Introduction to CSS Training course for free.

See the Course Outline and Register

Instructions

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>

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss