Welcome to our free Advanced CSS tutorial. This tutorial is based on Webucator's Advanced CSS Training course.
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.
Let's look at a simple example. Open ClassFiles/CSS101MediaQueries/Demos/index.html in a browser to check it out.
<!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>
The HTML markup for our page is simple: a div
(with id
main
) wraps two div
s with id
s item1
and item2
respectively. The CSS code on our page styles those two div
s 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:
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:
This tutorial is based on Webucator's Advanced CSS Training Course. We also offer many other CSS Training courses. Sign up today to get help from a live instructor.