The Viewport Meta Tag

Contact Us or call 1-877-932-8228
The Viewport Meta Tag

The Viewport Meta Tag

While not CSS (but, rather, HTML), the viewport meta tag is almost always used when implementing responsive design with CSS3 media queries:

<meta name="viewport" content="width=device-width">

The viewport tag allows us to scale the width of our pages to match the screen width of the device. We can also set the initial scale of the page - that is, how zoomed-in or -out the page appears, with the initial-scale attribute:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

The initial-scale=1.0 value indicates that we want the page to be scaled to 100% when loaded; we could, of course, change this to 1.5 (for scaling of 150%) or some other value.

The viewport meta tag should be placed in the head of the page.

A First Example

Let's look at a simple example. Open ClassFiles/CSS101MediaQueries/Demos/index.html in a browser to check it out.

Code Sample:

CSS101MediaQueries/Demos/index.html
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
	<title>Media Queries Example</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<style>
		div#main {
			width: 70%;
			margin: 0 auto;
		}
		div#item1 {
			width: 48%;
			float: left;
			background-color: #f00;
		}
		div#item2 {
			width: 48%;
			float: right;
			background-color: #00f;
		}
		p {
			color: #fff;
			padding: 1em 0;
			text-align: center;
			font-size: 2em;
		}
		@media screen and (max-width: 900px) {
			div#item1 {
				float: right;
				background-color: #f88;
			}
			div#item2 {
				float: left;
				background-color: #88f;
			}
		}
	</style>
</head>
<body>
	<div id="main">
		<div id="item1">
			<p>I am item <em>one</em></p>
		</div>
		<div id="item2">
			<p>I am item <em>two</em></p>
		</div>
	</div>
</body>
</html>

Code Explanation

The HTML markup for our page is simple: a div (with id main) wraps two divs with ids item1 and item2 respectively. The CSS code on our page styles those two divs to present item 1 as a red-background rectangle on the left (via the CSS code float: left) and item 2 as a blue-background rectangle on the right. We style the paragraph inside of each div with some padding, color (white), and a fairly-large font size.

Here's the page with a browser width of about 1200 pixels:

wide

Our media query targets a max-width of 900 pixels; that is, the two CSS rules contained within our media query will apply for only viewing panes less wide than 900 pixels. In this case, that means that, when the browser is narrower than 900 pixels, the original rules for the two div elements are overwritten by the rules inside the media query: the float is swapped (item 2 is floated left, and item 1 is floated right), and the background colors are changed to a more muted red and blue:

narrow

Next