Tuesday, November 18, 2008

Creating a Reusable Three-column Layout using Compass

Let's pretend we want to build a three column layout like so: Using blueprint, the page is divided into 24 columns. In just a few minutes we whip out our three column layout for our webpage:
<html>
<head>
<link rel="stylesheet" href="stylesheets/screen.css"
type="text/css" media="screen, projection">
</head>
<body class="content">
<div class="container">
<div id="header">
This is the header
</div>
<div id="context-menu">
This is the left side
</div>
<div id="content">
This is the content of the page
</div>
<div id="some-ads-and-stuff">
This is the right side
</div>
<div id="footer">
This is the footer
</div>
</div>
</body>
</html>
And here's our stylesheet that implements this layout:
@import compass/reset.sass
@import blueprint/modules/grid.sass
body.content
.container
+container
#header, #footer
+column(24)
#context-menu
+column(5)
#content
+column(11)
#some-ads-and-stuff
+column(8, last)
Again, this is as easy to use as blueprint, but we've avoided making the mistake of putting presentation in our content. Now let's say you have several different templates and you've been good about making nice semantic names for the different pages and none of the IDs are the same. But we want all of these pages to use the same layout. This is where your power to create abstraction comes in. Using Sass you can define your own mixins that you can reuse! So you start by defining a three column mixin:
=three-column(!header, !left, !center, !right, !footer)
#{!header}, #{!footer}
+column(24)
#{!left}
+column(5)
#{!center}
+column(11)
#{!right}
+column(8, last)
Now you can now simplify your layout declaration even further:
body.content
.container
+container
+three-column("#header", "#context-menu", "#content", "#some-ads-and-stuff", "#footer")

No comments: