How to make a web page responsive with css

Before we begin you need to add the following to the head section of your html

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

Lets take a simple example of html:

<div class="container">   
  <div class="col-1">  
  </div>   
  <div class="col-2">   
  </div> 
</div>

So, lets say that we will have a webpage that will have 2 columns, one on the left and one on right. When the page gets too narrow, the right column can hop over to underneath the left column.  Here is the non-responsive css:


body{
  background: #0000FF;
}
.container{
  width: 970px;
  margin: 0 auto;
}
.col1, .col2{
  width: 50%;
  float: left;
  background: #fff;
}

/* make the float stop after col2 */
.col2:after{
  content: '';
  display: block;
  clear: both;
}

Our container divs width is set to 970px so when the screen resolution becomes less than that we can make some responsive css magic happen. First thing we will need is a media query.


@media (max-width: 969px){ /* 1px less than container width */
  .container{
    width: 100%;
  }
}

Now when the browser window gets to 969px wide the container div will no longer be 970px but instead 100%. At this width, it doesn’t seem worth doing anything with the column divs yet, so lets wait until the browser width gets to 640px.


@media (max-width: 640px){ 
  .col1,col2{
    width: 100%;
  }
}

And there you go. Very simple!

That was obviously a very basic responsive web page but you get the idea. With so many smart phones and tablets out there these days,  there are many screen resolutions that a responsive website needs to be adapted for. Check this out to find more resolutions

Leave a Reply


+ nine = 11

goin up