Try Tuts+ Premium, Get Cash Back!
A Basic Responsive Grid (Plus Handy CSS3 Media Query Reporter)
videos

A Basic Responsive Grid (Plus Handy CSS3 Media Query Reporter)

Tutorial Details
  • Topic: Responsive Web Design
  • Difficulty: Beginner
  • Screencast duration: 28 mins

Responsive web design is here to stay. Jeffrey Zeldman’s press, A Book Apart, has published a book by the name. The HTML5 Boilerplate has responsive elements built into its code base. Everybody and their uncle is promoting their new responsive web template.

Why? Because responsive design allows us to address the needs of many (and conceivably all) screen sizes — from small handhelds to tablets to desktops to giant widescreen monitors — all with one code base.


The Magic is in the Media Query

With the advent of CSS3 Media Queries, we have the ability to create CSS rules designed specifically for a variety of screen sizes. These rules wait in the wing, only being called upon IF and WHEN the device fits the parameters of the media query. As Andy Clarke has written, in his excellent 320 and Up, these media queries make it possible to:

load assets and layout styles progressively and only as they’re needed

Thus, it becomes possible to produce a single “device agnostic, one web boilerplate” for your designs.


It’s a Beautiful Thing

In this short tutorial, I’ll provide both a basic review (or introduction) to the basic concepts of responsive design while building a handy CSS3 Media Query Reporter which you may find handy in your future design projects. (I know I have.)

Then, using that reporter, we will take a first step toward converting a fixed-width grid system into a fluid and responsive grid system. We won’t build the entire grid today, but we’ll gain the concepts which will prepare us to do so.

What we’ll do here:

  • Start with a very basic grid.
  • Create a little CSS3 Media Query Reporter.
  • Make our grid fluid instead of fixed.
  • Add a media query to help the grid adjust to small screen widths.

This will equip us with concepts and tools to help us tackle the bigger steps to come.


1: Introduction

In this brief video, I’ll show you what we’ll create today.


Download the video, or subscribe to Webdesigntuts+ screencasts via YouTube

2: A CSS3 Media Query Reporter

One of the small challenges in building a responsive layout is deciding when to have certain rules apply.

For instance, at what point will your site make the transition from a single narrow column for handheld devices to a multi-column design? Will you have one big transition (from one-column to many-column), or will you provide an intermediate step or two along the way (one-column, two-column, 8-column, and so on)? And if you want to supply intermediate steps — WHEN will they apply? At 480 pixels wide … 768 … 1024?

One thing that can be helpful in making these decisions is an on-screen media query reporter, which can provide visual feedback as we cross each width threshold.

Let’s use CSS3 media queries to build ourselves just such a tool.


Download the video, or subscribe to Webdesigntuts+ screencasts via YouTube

Code for the Media Query Reporter

/* ======================================
	MediaQuery-Reporter Styles
========================================= */
body:after {
	content: "less than 320px";
	font-size: 300%;
	font-weight: bold;
	position: fixed;
	bottom: 60px;
	width: 100%;
	text-align: center;
	background-color: hsla(1,60%,40%,0.7);
	color: #fff;
}
@media only screen and (min-width: 320px) {
	body:after {
		content: "320 to 480px";
		background-color: hsla(90,60%,40%,0.7);
	}
}
@media only screen and (min-width: 480px) {
	body:after {
		content: "480 to 768px";
		background-color: hsla(180,60%,40%,0.7);
	}
}
@media only screen and (min-width: 768px) {
	body:after {
		content: "768 to 1024px";
		background-color: hsla(270,60%,40%,0.7);
	}
}
@media only screen and (min-width: 1024px) {
	body:after {
		content: "1024 and up";
		background-color: hsla(360,60%,40%,0.7);
	}
}

3: Toward a Fluid Grid

With our Media Query Reporter ready, we can use the same basic concepts to build a responsive grid system. In this brief tutorial, we will only take an initial step, but it will get us started in the right direction.

In the downloaded file, style.css, I’ve provided a very basic version of the grid system that comes with the awesome Twitter Bootstrap framework. By stripping it down to just a few lines, we can easily get a handle on what it takes to convert a fixed-width grid to a percentage-based fluid grid.


Download the video, or subscribe to Webdesigntuts+ screencasts via YouTube

CSS for the Original Pixel-Based Fixed Grid

	.container {
		width: 940px;
		margin: 0 auto;
	}
	.row {
		margin-left: -20px;
	}
	[class*="span"] {
		display: inline;
		float: left;
		margin-left: 20px;
	}
	.span-one-third {
		width: 300px;
	}

CSS for a Fluid Version of the Grid

.container {
		margin: 0 40px;
	}
	.row {
		margin-left: -3%;
	}
	[class*="span"] {
		display: inline;
		float: left;
		margin-left: 3%;
	}
	.span-one-third {
		width: 30%;
	}

4: Media Queries

A fluid grid is a start. But even a fluid grid has its limitations.

Once the screen size becomes too narrow, it does not allow enough room for three columns to live comfortably side by side. This is where the media query comes to the rescue.

In this next video, we’ll complete our basic grid system by providing a single transition. At widths smaller than 768px wide, our design will have a single column, so that the content can easily flow vertically down a narrow screen. But once we have a screen size that is at least 768px wide, the three-column layout will kick in, allowing us to make efficient use of the available screen space.


Download the video, or subscribe to Webdesigntuts+ screencasts via YouTube

CSS for our Fluid & Responsive Grid

.container {
		margin: 0 40px;
	}
	.row {
		margin-left: -3%;
	}
	[class*="span"] {
		display: inline;
		float: left;
		margin-left: 3%;
	}
@media only screen and (min-width: 768px) {
	.span-one-third {
		width: 30%;
	}
}

Conclusion

Obviously, we will need to do more work to create a full-fledged responsive grid-system. But it will be more of the same kind of work we’ve already begun. With the above concepts in tow, the remaining steps are not difficult. I intend to return with a demonstration of the full process in a later tutorial.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://martealdesigns.com bob marteal

    Oh, the media query reporter is great! Super simple and really useful. Seriously, thanks.

  • http://www.endlessstudio.com Min Kim

    Sweet!
    There are many Media Query tutorial out there, but this one is very simple and straight forward. Thanks!

  • GUILHERMAN

    the demo’s link doesn’t work :(
    fix the link, plz

    • http://www.snaptin.com Ian Yates

      Sure? I don’t have any problems with it.. :|

  • Dougieladd

    Really well explained. Agree with Bob fully! Thanks.

  • Pingback: Media Query Tutorial Published at WebDesignTuts+ | Web Design 2011-12

  • http://flashjourney.com/ Mahfoodh

    Ian,
    This is exactly what I need to learn to make my wordpress themes more geared for this. Thanks for this great tutorial.

  • Pingback: A Basic Responsive Grid (Plus Handy CSS3 Media Query Reporter) | Shadowtek | Hosting and Design Solutions

  • Pingback: A Little CSS3 Media Query Reporter | a Little Code

  • http://kustomdesigner.com Mike

    Great tutorial and now I’m trying to play around with it to see what I can come up with using a structure like this but could you please explain someone what this is: [class*="span"] . This is the first time Ive ever seen something like this and it makes no sense to me> I notice it’s using the universal symbol but as far as using brackets in my Css, Ive never done that before.

    • http://www.snaptin.com Ian Yates

      Hi Mike – good question, it’s an attribute selector. The syntax is E[foo*="bar"], which basically selects any element (E) whose attribute (foo) contains (*=) the sub-string (bar).

      In this case, it looks for any element (no specific element is defined) whose class attribute contains the sub-string span.

      It targets this div:

      <div class="span-one-third">

      but would also include this (for example):

      <section class="span-full">

      I hope that’s clear! If not, you can always check out the spec at w3.org :)

    • http://alittlecode.com David Cochran
      Author

      Mike,
      Ian’s exactly right. In the full-blown grid system used by Twitter Bootstrap, there are classes such as span1, span2 and so on through span16. With this attribute selector (which has been available since CSS2.1 and is supported by IE7 and up), it’s possible to select all of those classes in one fell swoop.

  • http://www.sparked.biz Geoffry

    Excellent tutorial! A few weeks attended the HTML5 conference in NYC & this responsive design concept was definitely featured.

  • dj

    Very timely – and nifty “reporter” trick. Good job.

  • http://alittlecode.com David Cochran
    Author

    Hi all,
    Thanks for the comments. And I’m glad that the little reporter is proving handy!

  • http://alexismejias.com alex

    For some reason Firefox isn’t displaying the 320 message, anyone got any clues?

    Chrome works fine

    • http://alittlecode.com David Cochran
      Author

      Hi Alex,
      It’s working for me in Firefox, releases 7 and 8 (Mac), viewing the demo linked to the tutorial.

      • http://alexismejias.com alex

        http://db.tt/ZvcPA1Qs

        I’m on win7 running FF7.1 for some reason not even the demo works, wonder if it is a bug. I’ll update to latest version later and report

  • Mecha

    Impeccable sir. I was just thinking about this today. When will the rest of this tutorial be out? Soon I hope. Thanks!

  • Brad

    Excellent tut. So many good things you can do with CSS

  • http://www.madliberation.net Steve

    Wonderful tutorial, thank you for sharing this with others.

  • http://robertjezyk.com robert

    Excellent tutorial,
    wonderful simplicity, just in time for me.

  • Pingback: Land-of-web » Weekend Reading №5 (12-02-2011)

  • Pingback: Tweet-Parade (no.48 Nov-Dec 2011) | gonzoblog.nl

  • Ian

    Wow, thanks! I had no idea this was so easy. You do the videos well and explain things well.
    Should be real easy to apply to other grid systems in the same way.

  • http://alittlecode.com David Cochran
    Author

    Given the interest in it, the Media Query Reporter is now a live project hosted at Github:

    https://github.com/davidcochran/CSS3-Media-Query-Reporter

    Feel free to come grab the latest there, and contribute any improvements.

  • http://www.softwarenology.com Marcos Quiros

    Excellent article! Very useful for those of us who will likely end up using a fluid-responsive CSS framework anyway but like to know how they work too. I had never seen the E[foo*="bar"] selector, I guess that is something else I learned today. Than you!

  • Pingback: responsive webdesign by benoittalbot - Pearltrees

  • Pingback: 2011年を振り返り、WEB屋として腐らんばかりの「ありがとう!」を伝えたい記事、サイト全部 [Part 1] | バンクーバーのWEB屋

  • Ivo

    I may be wrong but except the “min-width” media property, shouldn’t we also have “max-width” specified, e.g. “min-width: 480px and max-width: 767px”.

    If we don’t specify the max-width limitation, then for resolution of 1000px all of the media queries for min-width: 480, min-width:768, min-width: 960px will be executed where we only want the last one. Therefore we should limit the previous ones by specifying max-width of 767px and 959px.

    Please correct me if that’s not the case.

    Thanks. :)

    • http://www.snaptin.com Ian Yates

      Hi Ivo, you certainly can specify min and max values, and that will restrict whatever rules you use within those boundaries.

      It’s not required though. In a situation such as this (for example):

      @media only screen and (min-width: 480px) {
          h1 {
              font-size: 2em;
              font-weight: bold;
          }
      }
      @media only screen and (min-width: 768px) {
          h1 {
              font-size: 2.5em
          }
      }
      

      specificity takes control and the latter font-size overrules the former. In both cases though, the screen width is greater than 480px, and so the font-weight remains bold.

      Very soon I’ll be reviewing A Book Apart’s Mobile First which discusses this process of designing for smaller devices first, then progressively enhancing for larger screens (and arguably more capable machines). For example:

      @media only screen and (min-width: 480px) {
          h1 {
              font-size: 2em;
          }
      }
      @media only screen and (min-width: 768px) {
          h1 {
              background: url(image.png);
          }
      }
      @media only screen and (min-width: 1024px) {
          h1 {
              text-shadow: 0.1em 0.1em #333;
          }
      }
      

      The greatest screen size has accumulated all the properties..

      Hope that makes sense!

      • http://twitter.com/jitendravyas Jitendra Vyas

        What is the difference between “screen” and “only screen”? can you explain in detail with example?

        • http://www.snaptin.com Ian Yates

          Hi Jitendra, only is an additional keyword added to prevent older browsers (IE8 and older – check out this support table) from processing the rules within the media query.

          Take this, for example:

          @media screen and (max-width: 480px) {
              div.container {
                  width: 100%;
              }
          }
          

          Older browsers don’t understand the query parameters. They would interpret this as reading:

          @media screen {
              div.container {
                  width: 100%;
              }
          }
          

          and would therefore process the styles. By kicking off the query with the only keyword:

          @media only screen and (max-width: 480px) {
              div.container {
                  width: 100%;
              }
          }
          

          older browsers effectively see this:

          @media only {
              div.container {
                  width: 100%;
              }
          }
          

          which they don’t understand, as there’s no media type of “only”. This therefore hides the entire media query from older browsers. You can read more about the media query specification over on w3.org. Hope that helps :)

      • Ivo

        Hi Ian,

        That makes sense but I guess it all depends on the specific scenario you are dealing with. I was thinking for a situation when you have one background image (small) for your smallest layout, another image for your medium layout and another for your largest layout. In that case, you wouldn’t want to download all of them but only the one for the current layout.

        However, if you declare your media queries in ascending order then I guess it won’t be much of a problem to download a few more images when you are on a larger layout because that’ll probably probably mean you’re on a high speed network access too.

        Nonetheless you should always avoid making extra http requests and I still think you should specify both min-width and max-width when you are targeting mobile devices and if you are using background images (to avoid extra bandwidth and http request).

        • http://www.snaptin.com Ian Yates

          Yep – dead right, it’s certainly worth bearing in mind when arranging media-queries (if arranging is the right word..)

          There’s still plenty of hot discussion about the merits of mobile-first, and what exactly the best approach to RWD should be. Check out the thread Paul Irish started over on GitHub if you’re interested :)

  • http://twitter.com/jitendravyas Jitendra Vyas

    “Once the screen size becomes too narrow, it does not allow enough room for three columns to live comfortably side by side.”

    Because you are not reducing the font size of headings

    • http://www.snaptin.com Ian Yates

      …mmm not necessarily. There are more things to consider, such as line length.

      Three columns on a tiny screen would result in short, unreadable lines of text. For optimum readability we should be aiming for lines of text to contain around 66 characters, so it’s common to see multiple columns become one on smaller devices.

      Thanks for your input!

  • Pingback: Responsive Web Design: Outils, articles, templates. | | Responsive Design |

  • Nuruzzaman Sheikh

    Very well written. Thanks for sharing

  • Pingback: Timothy’s Tips #1: Smaller Devices | Webdesigntuts+

  • http://jide.fi Janne

    Hi,

    What do you think about my companys mobile site? Still working on it and it’s written in finnsih, but please take a look.

    http://m.jide.fi/

    thanks for the feedback :)

  • Pingback: Weekend Reading №5 (12-02-2011) « CSS Tips

  • Carolyn

    Wow thank you so much for this tutorial. I feel like I’m finally starting to grasp this a little bit more. I really look forward to your next tutorial continuing this however. Most likely when I build a site it won’t be this simple. But super excellent start to describing the basics and this is helping get a grasp on the whole concept. I learned a ton and also reading the comments is very informative also. Thanks Ian Yates for answering everyone’s questions. And David Cochran please let us know when the next tutorial is posted!!

  • Toby

    I can see why you have set the container to be set with these rules but if you were following Ethan Marcotte’s would they look like this:

    .container {

    margin: 0 40px;
    }

  • Toby

    I can see why you have set the container to be set with these rules but if you were following Ethan Marcotte’s would they look like this:

    .container {

    margin: 0 40px;
    }

  • Toby

    *Sorry about the posts above – not sure what happened there.

    I can see why you have set the container to be set with these rules but if you were following Ethan Marcotte’s method would they look like this:

    .container {
    width: 97.9166666666666667%; /*940/960 */
    margin: 0 4.166666666666667%; /*40/960 */
    }

    Or would you still not set a width to ensure the grid is flexible?

  • Pingback: A Basic Responsive Grid Plus Handy CSS3 Media Query Reporter | Webdesigntuts+ – Nick Happen

  • Pingback: A Simple, Responsive, Mobile First Navigation | SCRiPTMAFiA.cO.IN

  • Pingback: A Simple, Responsive, Mobile First Navigation | How to Web

  • Pingback: My Stream | A Simple, Responsive, Mobile First Navigation | My Stream

  • Pingback: A Simple, Responsive, Mobile First Navigation | Shadowtek | Hosting and Design Solutions

  • Alaa Nayfeh

    Super awesome..
    thanks for this great tutorial.. but please.. i cant watch or download the last Vid.
    4: Media Queries
    i get the following message when trying to download

    Forbidden

    You don’t have permission to access /9370010356861/Webdesigntuts-Responsive4162.m4v on this server.

    Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

    • http://www.snaptin.com Ian Yates

      Hmm, sorry about that – blip.tv misbehaving again :( I’ve updated all the download links to point to our Amazon hosted versions. Have another go?

  • Pingback: Getting started with Responsive Web Design 100 articles and tutorials « CSS Tips

  • Pingback: A Simple, Responsive, Mobile First Navigation | Webdesigntuts+

  • http://www.psrdesignsolutions.com Patricia Rios

    I am in LOVE with this tutorial. I thought this story of grids and responsive webdesign was too complicated until i had the blessing of finding your tuto. hope you can feel bit of my gratitude for you!

    thanks!

  • http://webdesign-labor.de Rob

    I am doing my first project with media queries and this framework is just awesome!

    Easy to modify the containers to my needs (one large content area and tow narrower module columns)

    I love the “body:after” feature which maes it so comfortable to design.

    The project has several background images (for each menu-item one) which have to be modified for all the devices.

    I just started doing responsive webdesign after reading the book of mr. marcotte.

    I was quite confused about all the possibilities and this solution is just perfect for someone who starts.

    I have one question: Do I have to chance the “min-width” in “min-device-wdth” after testing and when going live?

    Anyway thanks for this great solution!

    Best Regards from Berlin (Germany),

    Rob van Linda

  • verpixelt

    First of all, awesome tutorial, thank u! I’ll use this a lot. There’s only one thing I dont understand. The “less than 320px” doesn’t work for me. Tested FF, Chrome and Safari. It doesn’t work in your demo either.

  • verpixelt

    First of all, awesome tutorial, thank u! I’ll use this a lot. There’s only one thing I dont understand. The “less than 320px” doesn’t work for me. Tested FF, Chrome and Safari. It doesn’t work in your demo either.
    OSX Lion, FF12.0, Chrome 19.0.1084.46, Safari 5.1.7 (7534.57.2)

    • Sussie

      The “less than 320px” doesn’t work for me ether.

      Tested in FF 12, Chrome 19.0.1084.54 and Safari 5.1.7 (6534.57.2) on OSX (Snow Leopard? not sure, but the one before Lion) 10.6.8

      • Cyd

        Same here. OSX Lion – tested in FF 12 and Safari (latest version) and the below 320px doesn’t work. Interestingly, if I remove the others queries, then it shows up, but as soon as I put even one back in, that’s the only one that shows and the 320px never does.

    • Mithat

      <320px doesn’t work for me in Iceweasel 10.0.6 (FF rebranded for Debian Linux). However, it does work on Chrome 21.0.1180.75 and Opera 12.01.

      I also tried inverting priorities (i.e., using max-width, reversing the order of sizes, and making >1024 the default) and observed the same: <320px worked on everything but Iceweasel. In this test, the smallest I could get Iceweasel to report was 339px.

  • PH

    Guys,
    What about IE7….
    I still need to support it, so wonder what would be the case for this horrible case when media queries do not work.
    ???!!!

    • http://twitter.com/jswebschmiede Jörg Schöneburg

      IE7 on a mobile phone? ;)

  • eric

    Please also include a cool navigation…..

  • Hem

    Yes, Both links are dead. Please fix it.

    Thanks

  • http://www.facebook.com/davewilliams.me Dave Williams

    Great little tutorial, thanks! :)

  • Ali Emre

    To understand the basics of responsive grid system, this article is full of help (I think), althoght it hasnt finished yet. Thanks a lot.

  • someone like you

    Great tutorial thx a lot!

  • Pingback: Responsive Design | Colin Squires

  • Pingback: 响应式设计的十个基本技巧 | 博客 - 伯乐在线

  • Pingback: Responsive 设计的十个基本技巧 | 5迷3道 | HTML5和CSS3的真材实料

  • Pingback: 响应式设计的十个基本技巧 | 西安网页设计师

  • Pingback: 转载:Responsive设计的十个基本技巧 | Yuan Peng`s Tech Blog

  • Pingback: A Simple, Responsive, Mobile First Navigation « Web Design

  • Pingback: A Simple, Responsive, Mobile First Navigation « Mary Brija

  • Pingback: A Simple, Responsive, Mobile First Navigation « glindemulder

  • Pingback: Media Queries.. | Sathya's Log

  • Pingback: Week 10 – Lecture & HomeWork – Implementation of Media Queries | IMD 215 @ AiTN

  • Pingback: Jer's Life » How I Learned HTML & CSS

  • Pingback: Handy CSS3 Media Query Reporter