This is just a fancy way of describing how a website behaves based upon the device and browser resolution. In short, an “if-else” statement built around CSS. If the viewport is less than 960px wide, use this CSS; if the viewport is less than 640px wide, use this CSS… and so on. It’s actually quite simple, but clearly you’ll need to work around the logistics of design and functionality across all of the possible viewport sizes you wish to accommodate. (Link to a demo at the bottom!)

Implementing a responsive web design requires the use of media queries, a feature of CSS3. First, declare the usage of viewports:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--[if lt IE 9]>
   <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
<![endif]-->

Then let’s declare the CSS to something simple like a container div:
#container {
   width: 960px;
   height: 250px;
   border: 1px solid black;
}
@media screen and (max-width: 680px) {
   #container {
    width: 640px;
    height: 250px;
    border: 1px solid blue;
    }
}

The above CSS statements go inside the <style> tags, and the container div will default to 960px wide. If the browser/viewport decreases to 680px wide or less, then the container div will reduce in width to 640px, and the border will change from black to blue. Simple, right?

Real World Implementation

Clearly, it doesn’t make sense to “double” or “triple” CSS declarations for the respective number of viewport sizes you want to accommodate – it’ll get confusing and be a mess. So, what’s the best way to implement this? I’ve found it best to create a separate stylesheet for each viewport, then have them imported into the main HTML file. Here’s what I mean:

Declare multiple CSS files:
<style>
   @import url('css/style.css');
   @import url('css/980.css');
   @import url('css/640.css');
   @import url('css/480.css');
</style>

style.css: (default stylesheet to use for viewports wider than 980px)
#container {
width: 960px;
height: 250px;
margin: 20px auto;
border: 1px solid black;
}

980.css:
@media screen and (max-width: 980px) {
#container {
  width: 640px;
  height: 250px;
  margin: 20px auto;
  border: 1px solid red;
}}

640.css:
@media screen and (max-width: 680px) {
#container {
width: 480px;
height: 250px;
margin: 20px auto;
border: 1px solid blue;
}}

480.css:
@media screen and (max-width: 500px) {
#container {
width: 320px;
height: 250px;
margin: 20px auto;
border: 1px solid green;
}}

See It In Action

Demonstration

Share: