Responsive Web Design Using Compass [Revised]

How to build a responsive grid with compass

The responsive web design comes as a solution to better display content across tablets, mobiles phones and laptops of the most varied screen sizes and resolutions. In order to achieve a responsive layout, all we need is: a Flexible grid, Flexible Content (Images and Media) and CSS Media Queries.

The use of these three main elements makes it possible for us to create websites that respond to the device or browser window size, adjusting the content accordingly in order to offer a better reading experience, should you be hunching over an iPhone on a busy train or comfortably sitting in front of a 30″ LCD shopping for dog food.

This is an experiment that combines the Responsive Design Layout practices to the Compass/Sass framework, in an attempt to cut back on the time and effort needed to achieve a Responsive web page.

Live demo Sample code

What is Compass/Sass?

Compass is an open-source CSS Authoring Framework originally created to enable the use of Blueprint framework with Sass. Since then, Compass has become a “Swiss Army Knife” of tools and utilities with a crescent list of plug-ins that makes it possible to combine different frameworks in one project with ease. Most of the famous frameworks, such as: 960gs, Boilerplate, Less Framework are already available for Compass.

Sass is the language in which Compass is built upon – Try not to mix Sass language and SASS syntax. Sass compiles the style-sheets and bring some powerful features for CSS writing, such as mixins, functions, variables, efficient nesting of selectors, properties and much more.

Compass and Sass have co-evolved to become a powerful and versatile platform – many current features of Sass has been driven by Compass.

Sass Syntax

Sass offers two syntaxes for us to use. The SASS Syntax (yes, same name) and the SCSS Syntax.

The SASS syntax is the first one created. It is a white space aware and indented syntax that instead of brackets and semicolons, it uses indentation to specify blocks; and tabulation to specify nesting. It is the syntax used on the sample code provided.

Although SASS was the first syntax offered, it does not mean that it is a deprecated one. Both syntax are current and will be always supported.

The SCSS – or Sassy CSS, is a newly created syntax to be a super-set of CSS3. It means that a valid CSS3 stylesheet is also a valid SCSS. You can even paste your CSS into a SCSS and it will be compiled just fine. There are some differences between the two syntaxes in terms of the use of mixins and includes, but even the busiest developer can start using Compass in their next project with no need to learn another syntax.

I personally think that CSS isn’t a wise syntax and I appreciate typing less, that’s why I use SASS instead of SCSS. However, it is just a matter of which one you want to go with. As Nathan Weizenbaum , Sass Language creator and maintainer posted about: The Indented Sass Syntax is Here to Stay

You can try the SASS syntax online.

Why use Compass?

Compass will massively cut back the amount of code you will need to write, simplify the maths and give you much more control over the grid. Furthermore, you won’t need to clutter your markup with semantic-less rubbish or cripple your project scalability and changeability.

For example, that’s how we would use 960gs without Compass:

<div id=”main” class=”grid_9”>
  <article class=”grid_6 alpha”>
  </article>
  <aside class=”grid_3 omega”>
  </aside>
</div>

Notice all the extra classes you have added to your markup. If you need to change the design later on, you will need to go after these classes and replace them. If you are using a complex PHP framework, it would be a nightmare to hunt them down in different templates, include files etc. Phew…

If you use Compass, you won’t need to add any additional classes to your markup. You will only need to use normal selectors to specify your grid:

#main
  +grid(9)
  +omega
  article
    +grid(6,9)
  aside
    +grid(3,9)
    +omega

That’s how your CSS will be compiled:

#main {
  display: inline;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
  width: 700px;
  margin-right: 0;
}
#main article {
  display: inline;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
  width: 620px;
}
#main aside {
  display: inline;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
  width: 300px;
  margin-right: 0;
}

Should you change your page layout later on, all you will have to do is to adjust the grid mixins on your .sass file and re-compile your CSS. Likewise, if you are looking for achieving a responsive layout, it will enable you to attribute different grid values to the same element using media-queries – that class won’t be on your way! It just makes life so much easier…

Not convinced yet? Compass brings tons of helpers and keeps you from repeating declarations for different browsers, different projects etc. Furthermore, you don’t have to collect and maintain an extensive library of snippets a-n-y-m-o-r-e! Time for the schmaltzy CSS lovers to look for another hobby.

Example:

I write:

div.mybox
  +border-radius(4px)
    a
      +replace-text("btn.jpg",50px,30px)

Compass writes for me:

div.mybox {
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  -o-border-radius: 4px;
  -ms-border-radius: 4px;
  -khtml-border-radius: 4px;
  border-radius: 4px;
}

div.mybox a {
  text-indent: -119988px;
  overflow: hidden;
  text-align: left;
  background-image: url('../images/btn.jpg');
  background-repeat: no-repeat;
  background-position: 50px 30px;
}

I needed to write 4 lines of code and Sass/Compass has written 16 lines of valid CSS code. This is just an example, see what Compass brings on its core.

Advantages

Besides the fact that it is free, the greatest advantage of using Sass/Compass is that it is designer friendly, easy to use, quick to install and very well documented. You don’t have to understand Ruby to make it work. If you know CSS and HTML, you are set and most modern code editors offer support to SASS/SCSS Syntax.

The output is just a neat and clean CSS ready to be deployed. Compass does not require any extra server configuration or client side requirements. Unlike lesscss, although it also enables you to use variables, mixins, operations etc, it relies on an additional JavaScript on the client or server side.

Compass is project aware. Besides the project configuration file that allows you to specify your project directories or use a relative path to the stylesheet, you can use a variable or url function to specify the url to asset hosts should you be serving over a web-server. It keeps your stylesheets safe from environmental differences.

Installation

If you are on a Mac, the installation is pretty straight forward. Open your Terminal and type:

$ sudo gem install compass

Type your password.

Then, to confirm the installation:

$ compass version

It’s been successfully installed if you read:

Compass 0.11.5 (Antares)
Copyright (c) 2008-2011 Chris Eppstein
Released under the MIT License.
Compass is charityware.
Please make a tax deductable donation for a worthy cause: http://umdf.org/compass

Windows

If you are using windows, you need to install Ruby first, then follow the steps above.

Susy Grid Compass’ Plug-in

For this experiment, I used Susy grid plug-in. It is the first time I am using Susy and it has proven to be the best fit for this project, as we have the option to not use side gutters and we can use percentage for achieving a flexible grid. I am quite convinced that Susy is, so far, the best grid I have worked with.

To install, you need to go on to your Terminal and type:

$ sudo gem install compass-susy-plugin

Remember to take some time to have a look at the Susy documentation, so you can better understand its usage.

Using Compass

Let’s say you are creating a new compass project using Susy. All you have to do is to open your Terminal, go to the directory of your choice and type:

$ compass create project_name -r susy -u susy --syntax sass

Note: if you don’t use –syntax sass, the project will be created using SCSS syntax by default.

If you are more familiar with the SCSS syntax, you can convert the SASS files I have provided using the command line:

$ sass-convert screen.sass screen.scss
$ sass-convert _base.sass _base.scss

To start working, you need to let compass know that you are changing your .sass files. To do that, you have to go to your project directory on Terminal and type:

$ compass watch

From now on, every time you save one of your .sass files, Compass will compile the .css file to the /stylesheets/ folder. All you have to do is to import this file into your HTML file.

While I was writing this article I found out that there’s a GUI for creating projects with Compass. I haven’t tested it yet, but if you find it hard to use the command line you can check it out. It runs on Windows, Linux and Mac.

Project Structure

Compass will create a folder called project_name, containing:

/config.rb
/sass/_base.sass
/sass/screen.sass
/stylesheets/ screen.css

The files with underscore “_” at the beginning are considered partials. The _base.sass, contains all the imports and the grid parameters that are to be imported at the top of screen.sass file. I also like to put the reset, all the varies, font-face and mixins in the _base.sass as well.

The screen.sass will have all our page styles followed by our media queries.

The config.rb will contain your project paths and will also have a few other configuration options that come briefly commented. It is a Ruby file and you can do quite a lot with it if you poke around. For example, when you finish your project you may want to compile your stylesheet in a minified version, then all you have to do is to use the declaration:

output_style = :compressed

If you are going to use relative paths and you are not using a local web-server, you will need to uncomment the line:

relative_assets = true

Remember to comment it out again when you deploy it to production. See more about the config.rb file.

Debugging on Compass

If you are not using the compressed output style, the CSS generated by Compass is organized and commented. If you inspect an element, the comments on the CSS file will refer you to the line of the .sass declaration that targets this element.

Whenever you save the file, if there’s something wrong, compass will tell you which line and which file you messed up.

If you are new to Sass, pay attention to the indentation. If you don’t use the same indentation or forget the correct spacing, it will not work.

Example:

It is fine to write:

#my_box
  float: left

But, it will not work if you forget the space between the attribute and the value:

#my_box
  float:left

I am just saying that because I have lost quite a few minutes cursing at the code as I couldn’t see anything wrong.

Getting into the Responsive Layout

This article exemplifies the combination of Vertical Rhythm and Susy Grid Frameworks to achieve a Responsive Layout using Compass to compile our stylesheets.

1. Defining the flexible grid

The flexible grid - 20 Columns

First of all, your mockup has to be organized into columns. You may already have your favorite grid. As I am used to the 960gs, I usually start all my designs using the .psd files provided by them – you can add columns manually if you need. The column width will give us the basis to find the relative values that will be used to configure our grid.

Susy allows us to choose the number of columns and gutter size according to necessity. For this layout we are using 20 columns. As our design has two background images that go across the browser window. I am trying something different here, we will not use margin to position the container in the middle of the window or use the grid side gutters. I have used the columns themselves to specify the space allowed between our content and the actual browser window sides, we will have better control of the grid across the devices.

Here’s what I mean by that:

Smaller and Bigger screens side gutter representation

The best thing about using a grid framework, is that we will not have to do these calculations for every element, margin and padding we need. For all the settings of width, we will use the grid.

Please, now open the file _base.sass.

$total-width: 1180px
$total-cols: 20
$col-width-abs: 40px
$col-width: $col-width-abs / $total-width * 100%
$gutter-width-abs: 20px
$gutter-width: $gutter-width-abs / $total-width * 100%
$side-gutter-width: 0

These are our grid constants, since our grid is going to be flexible, the width values are going to be in percentage, for doing that, all we have to do is to divide the column width by its context.

40px wide columns and 20px gutters size.

As our mockup is 1180px wide, we have 20 columns and each column is 40px wide, we use the following formula to calculate the grid percentages on-the-fly.

Finding the column width in percentage:

$col-width-abs: 40px
$col-width-abs / $total-width * 100%

To find the gutter in percentage we use the same logic:

$gutter-width-abs: 20px
$gutter-width: $gutter-width-abs / $total-width * 100%

Having done that, we now have our flexible grid. Thanks Tobias for the contribution.

Flexible Images

The textual content will flow naturally as we expand and contract our grid, but the images are still in need of a bit of CSS to assume a fluid quality. It is very simple, we can sort this out with one general declaration:

img
  max-width: 100%

This way, the maximum width the image will assume is its container width. We can also apply max-width to embedded videos and so on, so let’s make it more interesting:

img, embed, object, video
  max-width: 100%

If you still care about IE6, you better know that it does not support max-width. So, we need to use another declaration to go around it.

For this project, we are using a conditional <html> tag that gives us the means to fix some compatibility issues for IE. So, we will use the declaration:

.ie6
  img, embed, object, video
    width: 100%

It will make all the images take the whole width of its container, which may work just fine in most cases. For small images and thumbnails, you may need to use more specific declarations.

2. Implementing the Vertical Rhythm

Some might find it better to work the typography size also using percentage whereas, I prefer to have more control over the typography without having to worry about nested elements, relative values etc. For this reason, I decided to use the Vertical Rhythm, another framework that comes integrated with Compass.

It works like a vertical grid that makes it much easier to attribute vertical margin and padding to our page elements. It means that you can also design and distribute your typography and container heights following a vertical grid, or rhythm.

I like to configure my Photoshop grid as you can see below. Then, I can toggle the grid using the shortcut cmd + ” ‘ “.

Easy way to refer to the vertical rhythm on Photoshop

On _base.sass, we define the constants of our vertical rhythm:

$base-font-size: 14px
$base-line-height: 17px

It means that a due text line, if we don’t specify otherwise, will assume the font-size of 14px and the line-height of 17px as default values.

Vertical Rhythm size demonstration

Then, for all font size declarations we will use the mixin +adjust-font-size-to(font-size in pixels). Compass will then, convert the font sizes from px to em and fit it into the vertical rhythm automatically. Likewise, If you need to adjust the line-height, you will use +adjust-leading-to(number of lines).

Quick Reference

+padding-leader(1) – Adds 17px padding to the top of a due element.
+padding-trailer(1) – Adds 17px padding to the bottom of a due element.

+margin-leader(1) – Adds 17px margin to the top of a due element.
+margin-trailer(1) – Adds 17px margin to the bottom of a due element.

+adjust-font-size-to(32px) – Changes the font-size to 32px
+adjust-leading-to(2) – Changes the line-height to 34px

Note: The line height is relative to the constant $base-line-height: 17px – in our case the constant is 17px. The number you specify for the leader, trailer and leading will be multiplied by the constant, then converted to its relative value in ems. Don’t worry about nested elements etc, Compass will do the maths for you.

Find out more about the vertical rhythm usage.

Fix all the Weirdness

Right, we have created our flexible grid, made our images flexible and setup our vertical rhythm. But if you scale the screen you will face some weird columns, and line breaks that make no sense at all.

How flexible grids behave without Media Queries - Time to fix the weirdness

Our last step is to fix it all using Media Queries.

Media Queries

Media queries are expressions that allow us to target a group of CSS declarations to some specific device capabilities. If the device does not match to the query, the declarations are ignored. For example:

@media screen and (max-width: 480px) { ... }

In this case, the device has a screen 480px wide or less, the styles of this query are applied. If not, they are ignored.

You can also use the media-queries in sequence:

@media screen and (device-width: 768px) and (orientation: portrait) { ... }

See some more examples of media queries and read more about the W3C specifications.

Now, let’s take a look at the Media Queries used for this experiment:

@media screen and (max-width: 480px)

On this query we are basically re-arranging the main and secondary content area grid to assume one column layout and two columns layout for the footer.

Media Query - Max-width screen 480px - Content View

In devices with smaller screens, you may also want to adjust the typography. The vertical rhythm makes it simple. You can just override the Vertical Rhythm values at the beginning of each query. For this query:

$base-line-height: 16px
  +establish-baseline(12px)

Which sets the vertical rhythm from 17px to 16px for all devices with screens less than 480px wide. After this declaration, all typography, margin and padding will be automatically adjusted to the new rhythm, and the font baseline will be 12px by default. Just remember to use the Vertical Rhythm mixins to adjust the font size, leading, margin/padding leading and trailer, as I explained above.

Some may prefer to use percentage and assign relative values to the whole typography. I personally think that it can be a bit confusing, specially if you are collaborating on a project that may suffer revisions and you probably don’t want to spend too much time with maths.

The same happens for the grid values, as we don’t have those nonsense classes littering our markup, you can just attribute new grid values to every element according to necessity.

@media screen and (max-width: 710px)

This is an intermediary query that makes the footer go from two columns, to three columns, before assuming the four columns layout you can check when the browser window is wider than 710px. It also makes the transition from three columns to two, and finally, to one column on the #secondary container above the footer.

Media Query - Max-width screen 710px - Footer view

@media screen and (max-width: 840px)

The main call for this query is to keep the logo and the navigation from running into each other. When the screen is smaller than 840px wide, the navigation will appear underneath the centralized logo.

Media Query - Max-width screen 840px - Header view

@media screen and (max-width: 1024px)

Remember that we are not using side gutters, we were actually using a grid column to build space for the sides. For all screens 1024px wide or smaller are going to assume one column to the sides, while bigger screens are assuming two.

Media Query - Max-width screen 1024px - Content view

This Media Query also makes the transition from two to three columns of the main content, as well as re-adjust the Vertical Rhythm and font sizes.

@media screen and (min-width: 1500px)

This media query makes the page heading aligned to the center and sets another Vertical Rhythm.

Media Query - Max-width screen 1500px - Desktop overall view

The View-port meta element

The webkit mobile browsers comes with a default feature that scales the web content down to match the device width, even with a flexible grid and media queries in place.

To get around it, we need to add a meta element to the header of the html that will set the zoom of the page to 100% and match the browser size to the device screen size.

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

There are a few options that you may consider using for more specific situations.

Conclusion

My main concern in this experiment, was to make the transition between the devices iPhone, iPad and Desktop perform the best way possible, as well as keeping the layout flow as good as I could as you scale your browser window.

By using the max and min-width attribute, you will find a way to sort most of the issues by adding auxiliary queries in between.

Try commenting off the queries you will find in the sample code and see it for yourself. To comment in SASS and SCSS syntax, you need to add “ // ” in front of the lines you want to comment.

Compatibility

Media Queries are supported in most modern desktop browsers, including IE9. However, it does not work up to Internet Explorer 8. Thankfully there are people fixing Microsoft’s fails with a bit of JavaScript and the will to make web-designers happy.

Scott Jehl, developed a small script called Respond, that enables media queries support on Internet Explore 8 and under. Unfortunately, we need to rely on JavaScript for patching other IE versions, there’s no way around it.

Note: I haven’t added media queries fallback on the sample code.

Responsive web-design beyond the technique

This article has a strong focus on the technical part of how to build a responsive page. All I have done was to convert a non-responsive page, into a responsive one in order to achieve a framework that will offset the time needed to achieve a responsive page.

What I have learnt from this experiment, goes beyond the fact that the page adjusts itself to the width of the browser; we need to consider also the context in which the user is in while reading our content, what are the singularities of the devices and make the effort to offer the best experience possible.

Just as an example, I haven’t made many changes to the design at all. If you consider that on the iPhone, our user will need to tap the links with his finger, the footer may need a different solution for keeping the user from tapping in two links at the same time. What I am trying to say is that, if this page had been planned to be responsive from start, it would be designed quite differently in many aspects.

Therefore, the best way to achieve a responsive design is planning and wire-framing the experience for the devices you are targeting and the audience you are communicating with. There are those who believe that for different contexts, we need different markups, different contents. I believe it is a valid approach, the way to go will depend on your objective, the content itself and the audience.

This experiment will bring to you a different surgeworks.com soon enough, stay put with us and don’t forget to leave your comments.

Example of Responsive websites

forefathersgroup.com
hicksdesign.co.uk
simplebits.com
morehazards.com
massimobonini.com
10k.aneventapart.com

Read more about Sass, Compass and Responsive Web Design

Responsive Web Design by Etthan Marcotte
Responsive Web Design – Article by Etthan Marcotte
compass-style.org
sass-lang.com
thesassway.com
susy.oddbird.net
nex-3.com