Apr 27 2016
Apr 27

typey has just turned 1.0, so I thought it would be a great time to show off some of its features.

With typey I set out to write an easy to use typography framework that didn’t try to reinvent the wheel of web typography - a viable replacement for Compass's Vertical Rhythm to help the move from ruby to node-sass. I wanted a clean and simple way to layout type and combine various css properties for consistent use. So often in front end development we are disecting various design files to interpret font sizes and line heights so we can then replicate them inside our sass as variables. Often we'll add to that our own custom maths to convert the values into relative units, or use something like Vertical Rhythm instead. typey does all that for you, and it's beautifully simple.

Define some defaults

You will start defining your various sizes as pixels (which are a joy to work with), and then typey will go ahead and convert them to relative units (either rems or ems). At its simplest you can define a base-font-size, a base-line-height-ratio, and then create a SASS map of font sizes, and typey will do the rest for you.

In the example below we’ve defined our defaults and started laying out type. The font-size map uses t-shirt sizes as best practice (but you can use any keys you like), and it makes keeping track and retrieving a large number of sizes a breeze. Typey will use ratio based unitless line-height, and spit out rem px fallbacks as needed (you can toggle them on and off). If you want to specify your own ratio for line-height you can do so too.

$line-height-method: ratio;

$base-font-size: 16px;
$base-line-height-ratio: 1.5;

$font-size: (
  xl: 32px,
  l:  24px,
  m: 16px,
  s: 12px,
);

html {
  @include define-type-sizing;
}

h1 {
  @include font-size(xl);
}

h2 {
  @include font-size(l);
}

Working with typefaces

New in typey 1.0 is the ability to define and recall typefaces. This is particularly handy when you have a few common properties you want to use consistently with a particular font family.

$sans-serif: "Helvetica Neue", Helvetica, sans-serif;

$typefaces: (
  sans-serif: (
    font-family: $sans-serif,
    letter-spacing: -.5px,
    weight: bold,
    case: uppercase
  );
);

h1 {
  @include typeface(serif);
}

Currently the typefaces map lets us set common font-family, letter-spacing, weight (font-weight) and case (text-transform) for an entire typeface. Of course the only required property is font-family, everything else can be skipped if it's not needed. Letter spacing is always outputted as an em value (calculated from the base-font-size) so it will be relative to your font-size.

Advanced typesetting

Another new feature in typey 1.0 are typestyles, which let us set a font-size, line-height, weight and case for elements. Think of a typestyle as a really convenient way to pair these properties so they are always expressed consistently.

$typestyles: (
  h1: (
    font-size: xl,
    line-height: 1.25,
    weight: bold
  ),
  h2: (
    font-size: l,
    line-height: 1.35,
  ),
  h3: (
    font-size: m,
    line-height: 1.5,
    case: uppercase  
  )
);

h1 {
  @include typeset(h1);
}

You can define any keys you like, with font-size being the only required property. The typeset mixin lets you recall any typestyle easily. In the above example I’ve used keys from the font-size map to define font-sizes however you can just as easily input pixel values instead.

Ratio vs Rhythm

You might notice at the top of the very first example is a variable where you can set a line height method. There are two options here: ratio and rhythm. This is where typey completely takes over from Compass’s Vertical Rhythm and lets you define a common unit of measurement (the base-line-height) and then set line-height, margins and padding as a multiple of that unit. And it’s really easy to use.

$line-height-method: rhythm;

$base-font-size: 16px;
$base-line-height: 24px;

h1 {
  @include line-height(2);
  @include margin(0 0 1);
}

Keep on using px

There is no reason you need to use multiples of base-line-height for spacing as typey’s font-size, line-height, margin, and padding mixins can all take px values and then do the conversions to relative units.

h1 {
  @include margin(4px 0 8px 25px);
}

Of course it’s not really best practice but handy none the less.

Debugging

To make things a little easier you can spit out debug grid lines that will give you a pixel perfect overlay to get things lined up exactly as you need to.

$typey-debug: true;
$typey-debug-color: red;

Just use the typeset (or type-layout) mixin and the grid code gets added automatically. When you’re done just turn off typey-debug. If you want to add debug lines to any element that isn’t using type-layout or typeset, you can do it manually as so:

h1 {
  @include typey-debug-grid(1);
}

The argument takes either a ratio or rhythm value depending on how you are working.

Pro tip: Use shorthand

The typefaces and typestyles maps accept shorthand so these can be even quicker to express. typey’s shorthand is very forgiving and you need only remember to include the font-family and font-size as the first values in each map.

$typefaces: (
  sans-serif: $sans-serif -.5px,
  serif: $serif
);

$typestyles: (
  h1: xl 1.25 bold,
  h2: l 1.35,
  h3: m 1.5 uppercase
);

Where to now

Although the typey website (typey.io) is not up and running yet, there is comprehensive documentation included in the repo inside each scss partial. So to get an in depth look at each mixin, variable and function typey uses take a look inside the stylesheets directory.

It’s on npm, ruby-gems and bower and it works great with either ruby-sass or node-sass (and eyeglass). Try it out now, you won’t turn back.

Checkout typey on github. typey is also included in Zen 6, so now is a great time to take a look.

Sass Front End Development typography
Jan 04 2016
Jan 04

Introduction

What if we had a Drupal theme that does exactly what we want? No more divs, in divs, in divs. No more weird css. Out of the box responsiveness, both adaptive as fluid. Debuggers, good javascript additions, Gulp. Maybe even a little styleguide generator.

That’s what we thought when we started working on our own custom Drupal starter theme in July 2013. We called it “FortyTwo”.

A brief history

Before we we started working with FortyTwo, we did theming, like many others, based on the Zen or Omega base themes. It worked, it got us where we wanted, but it had its downsides. Besides Zen we also looked at Omega and other major base themes. They all had their pros but also a lot of cons.

During a talk I had with one of the frontenders at Finalist about this we started to think: Why not create our own theme. Let’s combine all of the pros from all those themes to one, and maybe add some other nifty features.

The start

The first ever site we developed with FortyTwo, and the site that actually developed a big part of FortyTwo was the Finalist website. Back then it was a good starting point for us to develop website frontends the way we wanted to. Combined with good backend developers we could start working on good frontends.

Finalist.nl websiteThe Finalist website as built with FortyTwo

Because we developed FortyTwo as a base theme for Drupal we could use it to create all kinds of different websites, no matter the shape or size.

Features

Let me enumerate some of the best features FortyTwo has right now:

  • SASS; FortyTwo has completely been made using the SASS css preprocessor.
  • Drush integration; Easily create your sub theme using our custom drush command.
  • Out of the box responsiveness; Without no effort themes developed using FortyTwo are responsive. Both adaptive or fluid. Extending the responsiveness is easy by just copying some files. Want to change the breakpoints? They are defined in the sass settings file.
  • Gulp; We have added gulp support for some extra features.
    • SASS watch and compiling with auto prefixes for IE8 and IE9.
    • JSLint integration, while watching the theme folder the console will output errors or warnings from JSLint if there are any.
    • Uglify of JavaScript files.
    • Clearing of Drupal cache on changes in PHP, include or info files in the theme.
    • And last, but not least automatic reloading of the browser on file changes.
  • Icomoon integration; For easy development we have created a starter set of icomoon icons and added them to the theme. You can easily extend those icons and use theme using our custom icomoon SASS mixin.
  • Layout styles; It is possible to choose different styles of layout, whether you want your content column on the left, right or the middle, it is just a setting;
  • Debuggers; We have added some handy debuggers in FortyTwo:
    • It is possible to show the grid on the background of the page. The grid uses the settings set in the sass settings file.
    • It is possible to show a responsive identifier. This makes it easier to create responsive websites. A bar at the bottom of the website shows you on what breakpoint you currently are viewing.

Debuggers in actionThe above image shows the mentioned debuggers in action.

There is more, but you have to see for yourselves what FortyTwo can offer you!

Drupal 8

Since August 2015 we have also started developing the Drupal 8 version of the theme. Since Drupal 8 is becoming the new standard we wanted to be ready for it when it came out. On the date Drupal 8 was officially released FortyTwo was already finished and is now in active development.

I will write a separate blog about the porting of FortyTwo from Drupal 7 to Drupal 8 on a later date.

How about the future?

We are still in active development. Since the release of FortyTwo-8.x-1.0 Only bugfixes and really nice features are added to the Drupal 7 version of FortyTwo. Other new features are only added for Drupal 8.

On the roadmap are:

  • KSS; Knyle Style Sheets integration. Using KSS you can automatically create style guides from CSS and SASS.
  • FortyTwo admin theme; Admin themes are always difficult to pick. Because we work with a lot of clients, different kinds of content and content managers we believe that we can create a admin theme (of course based on FortyTwo) that suits the needs of everybody.
  • FortyTwo example theme; Since the start of development we always wanted to create a example theme that everybody can use, out-of-the-box.

Get involved!

Yes, we would love to see you around on the project page and the issue queue ! We heavily depend on your input, testing and feedback, but also on your commitment as a community developer, by helping us implementing new features and fixes.

Aug 28 2015
Aug 28

In my previous post I outlined how to build a Sass directory within a custom Drupal theme including Bourbon and Neat.

At this point, we’re ready to write some SCSS within the base, components, and layouts directories. In this post I’ll demonstrate how Savas Labs applies SMACSS principles to organize our custom SCSS. As a reminder, I’ll be linking to our Drupal 8 mapping site as an example throughout, but none of this is Drupal-8-specific.

Drupal-flavored SMACSS

When we left off, our sass directory looked like this:

# Inside the custom theme directory
sass
├── _init.scss
├── base
├── components
├── layouts
├── lib
│   ├── bourbon
│   ├── font-awesome
│   └── neat
└── styles.scss

At this point we’re ready to start styling. Let’s take a look at the three folders that will hold our custom .scss files, which are loosely based on SMACSS. Acquia has a nice writeup of how SMACSS principles can be applied to Drupal, but I like to simplify it even further.

Base

I personally only have three files in the sass/base directory. Don’t forget that we already imported these three partials in styles.scss.

For full examples of each of these files, check out our base directory.

_normalize.scss

This is simply normalize.css renamed as _normalize.scss - remember that CSS is valid SCSS. Thoughtbot recommends using normalize.css as your CSS reset along with Neat. Regardless of which reset you use, include it in base.

_base.scss

This is for HTML element styles only. No layout, no classes, nothing else. In here I’ll apply font styles to the body and headings, link styles to the anchor element, and possibly a few other site-wide styles.

_variables.scss

This is where I house all of my Sass variables and custom mixins. I typically have sections for colors, fonts, other useful stuff like a standard border radius or spacing between elements, variables for any Refills I’m using, and custom mixins.

I’d definitely recommend including _normalize.scss in base if you’re using Neat, but other than that do what works for you! If you’re following my method, your sass folder should be looking like this:

# Inside the custom theme directory
sass
├── _init.scss
├── base
│   ├── _base.scss
│   ├── _normalize.scss
│   └── _variables.scss
├── components
├── layouts
├── lib
│   ├── bourbon
│   ├── font-awesome
│   └── neat
└── styles.scss

Layouts

This directory holds page-wide layout styles, which means we’ll be making heavy use of the Neat grid here. This is flexible, but I recommend a single .scss partial for each unique template file that represents an entire page. Think about what works best for your site. For the sake of our example, let’s say we’re creating _front-page.scss and _node-page.scss. I like to also create _base.scss for layout styles that apply to all pages.

Remember that these styles only apply to the page’s layout! I occasionally find myself moving styles from the layouts directory to base or components when I realize they don’t only define layout. In these partials, you should be doing a lot of grid work and spacing. This is the entirety of my sass/layouts/_base.scss file on our mapping site:

/**
 * @file
 *
 * Site-wide layout styles.
 */

body {
  @include outer-container();

  main {
    @include span-columns(10);
    @include shift(1);
    @include clearfix;

    h1 {
      margin-top: em($navigation-height) + $general-spacing;
    }
  }
}

We’re almost there:

# Inside the custom theme directory
sass
├── _init.scss
├── base
│   ├── _base.scss
│   ├── _normalize.scss
│   └── _variables.scss
├── components
├── layouts
│   ├── _base.scss
│   ├── _front-page.scss
│   └── _node-page.scss
├── lib
│   ├── bourbon
│   ├── font-awesome
│   └── neat
└── styles.scss

Components

In SMACSS this is called “modules,” but that gets a little confusing in Drupal Land. This is for applying layout and theme styles to smaller chunks of your site, which in Drupal typically means regions. Create a separate partial for each region, or if you have several distinct components within a region, consider a separate partial for each of them.

Let’s say we created partials for the header, footer, and sidebar regions, plus one for non-layout node page styles. At this point, our sass directory is looking like this:

# Inside the custom theme directory
sass
├── _init.scss
├── base
│   ├── _base.scss
│   ├── _normalize.scss
│   └── _variables.scss
├── components
│   ├── _node-page.scss
│   └── regions
│       ├── _footer.scss
│       ├── _header.scss
│       └── _sidebar.scss
├── layouts
│   ├── _base.scss
│   ├── _front-page.scss
│   └── _node-page.scss
├── lib
│   ├── bourbon
│   ├── font-awesome
│   └── neat
└── styles.scss

Now we’ve got a nicely organized, easy to navigate Sass directory, ready to hold your styles and compile them into one beautiful CSS file!

But how do we ensure that our one CSS file really is beautiful? Check out my final post about best practices for writing Sass that you can easily maintain or pass off to another developer.

Aug 27 2015
Aug 27

In my previous post I outlined how to build a Sass directory within a custom Drupal theme including Bourbon and Neat.

At this point, we’re ready to write some SCSS within the base, components, and layouts directories. In this post I’ll demonstrate how Savas applies SMACSS principles to organize our custom SCSS. As a reminder, I’ll be linking to our Drupal 8 mapping site as an example throughout, but none of this is Drupal-8-specific.

Drupal-flavored SMACSS

When we left off, our sass directory looked like this:

# Inside the custom theme directory
sass
??? _init.scss
??? base
??? components
??? layouts
??? lib
?   ??? bourbon
?   ??? font-awesome
?   ??? neat
??? styles.scss

At this point we’re ready to start styling. Let’s take a look at the three folders that will hold our custom .scss files, which are loosely based on SMACSS. Acquia has a nice writeup of how SMACSS principles can be applied to Drupal, but I like to simplify it even further.

Base

I personally only have three files in the sass/base directory. Don’t forget that we already imported these three partials in styles.scss.

For full examples of each of these files, check out our base directory.

_normalize.scss

This is simply normalize.css renamed as _normalize.scss - remember that CSS is valid SCSS. Thoughtbot recommends using normalize.css as your CSS reset along with Neat. Regardless of which reset you use, include it in base.

_base.scss

This is for HTML element styles only. No layout, no classes, nothing else. In here I’ll apply font styles to the body and headings, link styles to the anchor element, and possibly a few other site-wide styles.

_variables.scss

This is where I house all of my Sass variables and custom mixins. I typically have sections for colors, fonts, other useful stuff like a standard border radius or spacing between elements, variables for any Refills I’m using, and custom mixins.

I’d definitely recommend including _normalize.scss in base if you’re using Neat, but other than that do what works for you! If you’re following my method, your sass folder should be looking like this:

# Inside the custom theme directory
sass
??? _init.scss
??? base
?   ??? _base.scss
?   ??? _normalize.scss
?   ??? _variables.scss
??? components
??? layouts
??? lib
?   ??? bourbon
?   ??? font-awesome
?   ??? neat
??? styles.scss

Layouts

This directory holds page-wide layout styles, which means we’ll be making heavy use of the Neat grid here. This is flexible, but I recommend a single .scss partial for each unique template file that represents an entire page. Think about what works best for your site. For the sake of our example, let’s say we’re creating _front-page.scss and _node-page.scss. I like to also create _base.scss for layout styles that apply to all pages.

Remember that these styles only apply to the page’s layout! I occasionally find myself moving styles from the layouts directory to base or components when I realize they don’t only define layout. In these partials, you should be doing a lot of grid work and spacing. This is the entirety of my sass/layouts/_base.scss file on our mapping site:

/**
 * @file
 *
 * Site-wide layout styles.
 */

body {
  @include outer-container();

  main {
    @include span-columns(10);
    @include shift(1);
    @include clearfix;

    h1 {
      margin-top: em($navigation-height) + $general-spacing;
    }
  }
}

We’re almost there:

# Inside the custom theme directory
sass
??? _init.scss
??? base
?   ??? _base.scss
?   ??? _normalize.scss
?   ??? _variables.scss
??? components
??? layouts
?   ??? _base.scss
?   ??? _front-page.scss
?   ??? _node-page.scss
??? lib
?   ??? bourbon
?   ??? font-awesome
?   ??? neat
??? styles.scss

Components

In SMACSS this is called “modules,” but that gets a little confusing in Drupal Land. This is for applying layout and theme styles to smaller chunks of your site, which in Drupal typically means regions. Create a separate partial for each region, or if you have several distinct components within a region, consider a separate partial for each of them.

Let’s say we created partials for the header, footer, and sidebar regions, plus one for non-layout node page styles. At this point, our sass directory is looking like this:

# Inside the custom theme directory
sass
??? _init.scss
??? base
?   ??? _base.scss
?   ??? _normalize.scss
?   ??? _variables.scss
??? components
?   ??? _node-page.scss
?   ??? regions
?       ??? _footer.scss
?       ??? _header.scss
?       ??? _sidebar.scss
??? layouts
?   ??? _base.scss
?   ??? _front-page.scss
?   ??? _node-page.scss
??? lib
?   ??? bourbon
?   ??? font-awesome
?   ??? neat
??? styles.scss

Now we’ve got a nicely organized, easy to navigate Sass directory, ready to hold your styles and compile them into one beautiful CSS file!

But how do we ensure that our one CSS file really is beautiful? Check in next week when I talk about best practices for writing Sass that you can easily maintain or pass off to another developer.

About the author

Anne Tomasevich

Recent posts by Savas

Drupalcamp Asheville - an all around success!

A step-by-step tutorial on setting up Bourbon and Neat and compiling it all with Compass.

We’re giving two presentations at Drupalcamp Asheville!

Aug 21 2015
Aug 21

Recently Savas Labs built a custom Drupal 8 theme using Bourbon for mixins and Neat as our grid framework, applying our favorite parts of SMACSS principles and focusing on creating organized, maintainable code. The result? Fast, easy coding and a relatively lightweight theme.

In this three-part series I’ll detail:

I’ll be pulling some examples from our Drupal 8 theme, but none of this is Drupal-8-specific and really, it’s not entirely Drupal-specific. These principles can be applied to any site. Much of the material in these posts is also largely a matter of opinion, so if you disagree or if something else works better for you, sound off about it in the comments!

Definitions

Let’s talk vocab.

Sass

A preprocessor for CSS. Sass offers functionalities not yet available in CSS like variables, rule nesting, and much more.

SCSS

“Sassy CSS.” Early Sass, with the file extension .sass, used a syntax quite different from the CSS syntax we’re already familiar with. Version 3 of Sass brought SCSS, returning to the same syntax as CSS and proving easier to use for most developers. Importantly, this means that valid CSS is also valid SCSS. Files ending with the .scss extension are written in SCSS. I still call them “Sass files”; please don’t be mad at me.

If you found that last paragraph terribly interesting, you should read this.

Partial

An SCSS file that is not directly compiled into a CSS file, but is instead imported into another SCSS file. A partial is denoted by the underscore that begins its filename (e.g. _base.scss).

Bourbon

A Sass mixin library by thoughtbot, inc. Bourbon makes Sass easier and more powerful by providing extremely useful mixins, meaning you don’t have to write them yourself. I particularly enjoy using Bourbon for CSS3 mixins, which allow me to use modern CSS3 modules without having to worry about vendor prefixes.

Neat

A lightweight grid framework written for Sass, also by thoughtbot. The best part of Neat, in my opinion, is the separation of content from layout that comes from defining layout in Sass files rather than template files. This makes your grid system easier to define, update and maintain and keeps your template files cleaner.

Now that we’re all dying to use these awesome things with Drupal, let’s set it up!

Create a Gemfile

We need to install Bourbon and Neat, which are both Ruby gems. We could do a quick gem install bourbon then bourbon install to create a folder of the entire Bourbon library, but this isn’t ideal if we’re ever going to be sharing this code since each developer (and deployment environment) will need to have these gems installed on their machine. Enter Bundler, a package manager for Ruby gems. Per the documentation, we only need to do a few things:

1. Install Bundler, which is a Ruby gem itself

$ gem install bundler

2. Create a Gemfile in our theme directory

$ cd my-custom-theme
$ touch Gemfile

…and list out all the gems our theme requires.

# Gemfile
source "https://rubygems.org"

gem 'compass'
gem 'sass'
gem 'bourbon'        # Bourbon mixin library.
gem 'neat'           # Bourbon Neat grid framework.

See Bundler’s documentation to read about specifying versions within your Gemfile.

3. Install all your dependencies.

$ bundle install

4. Commit the Gemfile and Gemfile.lock to ensure that everyone is using the same libraries.

$ git add .
$ git commit -m "Add Gemfile and Gemfile.lock"

Create a Sass directory

Within the theme directory, create a directory called sass. In here, create the following directories:

# Inside the custom theme directory
sass
├── base
├── components
├── layouts
└── lib

Install libraries

Now we can actually install the Bourbon and Neat libraries within our project.

$ cd sass/lib
$ bourbon install
$ neat install
$ git add .
$ git commit -m "Add Bourbon and Neat libraries"

Here’s what we’ve got now:

# Inside the custom theme directory
sass
├── base
├── components
├── layouts
└── lib
    ├── bourbon
    └── neat

Now that we’ve got our libraries set up, we need to actually import them so that they’re compiled into CSS.

Set up styles.scss

Create styles.scss in the scss directory. Inside styles.scss, we’ll import all our SCSS partials. View a working example of this here. I generally organize the imports in this manner:

/**
 * @file
 * Styles are organized using the SMACSS technique. @see http://smacss.com/book/
 */

/* Import Sass mixins, variables, Compass modules, Bourbon and Neat, etc. */
@import "init";
@import "base/variables";

/* HTML element (SMACSS base) rules */
@import "base/normalize";
@import "base/base";

/* Layout rules */
// Import all layout files.

/* Component rules (called 'modules' in SMACSS) */
// Import all component files.

We haven’t created any of these partials yet, but we will.

Some people may want to use Sass globbing here for brevity’s sake. I prefer not to as I find the file to be more readable without it.

Set up _init.scss

Within the sass directory, create a file called _init.scss.

In _init.scss we will (in this order):

  1. Import Bourbon (the mixin library) and Neat Helpers (Neat’s settings and functions)
  2. Set some overrides
  3. Import Neat itself
  4. Import fonts

You can view an example of a full _init.scss file here, but I’ll go through some of the highlights.

1. Import bourbon.scss and neat-helpers.scss

First we import all of Bourbon and Neat’s settings and functions, which are included in neat-helpers.scss.

// Import variables and mixins to be used (Bourbon).
@import "lib/bourbon/bourbon";
@import "lib/neat/neat-helpers";

2. Create overrides

Now we’ll override some of Neat’s settings and create our breakpoints.

// Turn on Neat's visual grid for development.
$visual-grid:       true;
$visual-grid-color: #EEEEEE;

// Set to false if you'd like to remove the responsiveness.
$responsive:    true;

// Set total number of columns in the grid.
$grid-columns:  12;

// Set the max width of the page using the px to em function in Bourbon.
// The first value is the pixel value of the width and the second is the base font size of your theme.
$font-size:     16px;
$max-width-px:  2000px;
$max-width:     em($max-width-px, $font-size);

// Define breakpoints.
// The last argument is the number of columns the grid will have for that screen size.
// We've kept them all equal here.
$mobile:   new-breakpoint(min-width em(320px, $font-size) $grid-columns);
$narrow:   new-breakpoint(min-width em(560px, $font-size) $grid-columns);
$wide:     new-breakpoint(min-width em(851px, $font-size) $grid-columns);
$horizontal-bar-mode: new-breakpoint(min-width em(950px, $font-size) $grid-columns);

3. Import Neat

Now that we’ve completed our settings, we’ll import the entire Neat library and our overrides will apply and cause the grid to function the way we want it to.

// Import grid to be used (Bourbon Neat) now that we've set our overrides.
@import "lib/neat/neat";

4. Import fonts

I like to include my fonts in this file to be consistent about how I’m importing my libraries (e.g. the Font Awesome library, which I’ve included in sass/lib). Some people might move this into a _typography.scss file or something similar, perhaps residing in the base directory. Do what feels right!

// Fonts -----------------------------------------------------------------------

// Noto Serif (headings)
@import url(http://fonts.googleapis.com/css?family=Noto+Serif:400,700);

// Open Sans (copytext)
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,700,400);

// Font Awesome (icons)
@import 'lib/font-awesome/font-awesome';

Compile!

We haven’t written any custom styles yet, but at this point we can compile our SCSS into CSS using Compass (which we included in the Gemfile earlier).

First we need to generate a Compass configuration file using compass config.

$ cd my-custom-theme
$ bundle exec compass config

Why did we use bundle exec? Running a Compass command as a Bundler executable runs the command using the Compass gem defined in our Gemfile. This way, if we decided to define a specific version of Compass within the Gemfile that potentially differs from another version installed on our local machines, we ensure we’re using that specific version every time we run a Compass command.

Now we can compile our Sass. Run this command from the root of your theme directory:

$ bundle exec compass compile

Running this command for the first time does two things:

  1. Creates a stylesheets directory containing styles.css, the compiled version of styles.scss.
  2. Creates a .sass-cache directory

Once we start writing our own Sass, we can have Compass watch for changes and regenerate styles.css as we code:

$ bundle exec compass watch

I usually open a new tab in my terminal and leave this command running as I’m styling.

At this point our Sass directory is looking like this:

# Inside the custom theme directory
sass
├── _init.scss
├── base
├── components
├── layouts
├── lib
│   ├── bourbon
│   ├── font-awesome
│   └── neat
└── styles.scss

Where do we go from here? In my next post, I tackle the base, components, and layouts SMACSS-based directories and the custom scss files they will hold. In a future post I’ll go through some of Savas Labs best practices for writing Sass that can be easily shared amongst team members and maintained in the long run.

May 21 2013
May 21
Backlit spaghetti (as in code)

This is an intervention.

CSS is pretty simple. Classes, IDs, elements and pseudo-elements, with style definitions attached to each. Calling it a "language" is a bit of a stretch (though preprocessors like Sass fit the bill).

But let's be honest, for years our stylesheets cascaded right on out to infinity.

Huge files with table-of-contents comments to try to make some sense of it — until a quick fix got pasted down at the bottom. Brittle style definitions relying on tight coupling with HTML structure. Pieces of styles being replicated here and there for different components with similar features, without any way to tell they were related in the CSS.

My stylesheets were like that too, because strategies for writing CSS had barely altered since the days when it was used to change the colors of the scroll bars in Internet Explorer. Luckily, in the past couple of years both CSS architecture and CSS preprocessors came into their own.

Jonathan SnookSMACSS, or Scalable and Modular Architecture for CSS, was developed by Jonathan Snook, a featured speaker at Drupalcon Portland. I'm really excited to get the opportunity to have Jonathan speak, not only because of my personally well-dog-eared copy of SMACSS, but because Drupal itself is adopting a SMACSS approach to its CSS.

I spoke with Jonathan about sustainable stylesheets and the future of SMACSS. For an even more detailed look, please join me at Jonathan Snook's featured Drupalcon Portland this afternon, Tuesday, May 21 at 4:30 PM.

IB: What's the biggest mistake you see people making when writing CSS?

JS: I think the biggest mistake is thinking of everything in the context of a single page. We're no longer just building sites with a design for a home page and an inside page. We're developing complex systems that need to work in a variety of contexts and we need a development approach that complements that.

SMACSSIB: What's the biggest "win" you see in using the SMACSS approach? Why should frontend developers change their approach to CSS?

JS: The biggest win is maintainability. The SMACSS methodology makes it easier to build larger projects by breaking things down into smaller components. Like the move from spaghetti code to MVC frameworks on the server side, this separation of concerns on the CSS side improves the process of putting a site or web app together.

IB: In the last part of your book, you talk about how the SMACSS approach fits in to work using a preprocessor like Sass. There have been a lot of developments in Sass in the past year — have they had any positive effects on your use of the SMACSS approach?

JS: With Sass, the introduction of placeholders was a positive step forward. Overall, Sass (and other preprocessors) are a great way to augment — but not replace — the way people write CSS.

IB: What are your thoughts on BEM? Do you see it as compatible with SMACSS?

JS: I see BEM as very compatible. BEM really enforces naming convention, which is a very important concept in SMACSS. They both take a modular approach to site development.

IB: What are you tacking next when it comes to CSS and frontend development? Will there be a "SMACSS Part Two"? Or something else entirely?

JS: I'd love to augment SMACSS with case studies and expand on some of the ideas in the book based on things that come up in the workshops I do. I'd also like to work on a prototyping/site development tool that uses the SMACSS concepts. We had built something like this when I was at Yahoo! that I think many people in the industry would find really useful. Hopefully I can find the time to work on it!

Image credit Flickr user stevensnodgrass. It's spaghetti! (As in code.)

Join Rootwork on Twitter, Facebook and SlideShare.

Learn about Rootwork's services for nonprofits and social change.

May 17 2013
May 17
Breakpoint: Snap!

Media queries are a key part of responsive web design, because they control at what width (among other things) different CSS rules kick in.

"Breakpoint makes writing media queries in Sass super simple," say Mason Wendell and Sam Richard, creators of the extension to Compass, and they're right. It's not surprising that we'd want them to present at Drupalcon, since design in Drupal, like web design everywhere, has been embracing responsive web design as a fundamental principle. (Side note: This website is in the midst of a responsive web design overhaul. Cobbler's children and all that.)

I spoke to Mason and Sam about how Breakpoint makes responsive web design even easier. Don't miss their Drupalcon Portland frontend session, “Managing Responsive Web Design with Sass and Breakpoint,” on Thursday at 10:45 AM.

IB: What motivated you to create Breakpoint? How has it changed your own workflow?

MW: Before Sass 3.2 came out I had written an article for The Sass Way that previewed some of it's new features, including the ability to use variables in media queries. I created an example that baked in some names for breakpoints into a kind of "master mixin" for media queries. On my next responsive project I put the theories I'd written for that post into practice, and found that I could refine that approach. If I assigned a variable to each media query first the approach would be very flexible. Then when noticed that I wrote min-width queries way more often than any other type I set up defaults that made creating media queries very fast.

MW: There was a side effect that I think is more useful though. By assigning names to each of my media queries I'm able to keep them in context in a much more effective way. If I some media queries to deal with the width of a nav element, and then later I add an item to that nav, I can change the value of that variable and all the associated queries are adjusted. This is even more effective when handing code back and forth within a team.

SR: Breakpoint was created with the motivation to ease many of the pain points of working with media queries in CSS. The biggest pain point that Breakpoint solves is providing meaningful semantics to your media queries. When building content based responsive sites, early in your design process two unrelated items may happen to break at the same points, but as your project grows, those points may change and a simple find and replace will have unintended consequences. This is probably the biggest workflow win to using Breakpoint, all of your media queries now have proper semantics.

SR: The other big win for my workflow is Breakpoint's no-query fallback, allowing me to very easily add in fallback code for any of the media queries I write.

IB: What can Breakpoint do that just assigning variable names to specific min-widths can't?

SR: For starters, Breakpoint handles much more than min-width queries. It is designed to be future friendly and currently supports all CSS level 3 and level 4 media queries. Additionally, it's syntax is easy to use to create complex media queries, including both and and or media queries. It has native handling for all of the different media query requirement for resolution (of which you need to write at least four different queries for currently) while just writing the standard. The no-query fallbacks are a huge win as well.

MW: The main benefit is that you can assign names and manage your media queries with variables. This helps you avoid having them scattered around your SCSS, and makes is easy to understand how they're related and affect each other.

MW: While Breakpoint is optimized for min-width because they're used most often it doesn't stop there. There are a number of shortcuts built in, for fencing min- and max- values, converting pixels to ems, and even vendor prefixed queries like resolution.

MW: We even created a way to Breakpoint to report back to you what queries are in a particular context. Singularity GS uses this feature to kind of magically create responsive grid systems.

SR: Of all of Breakpoint's features, probably the least used, but most powerful is Breakpoint Context. This allows you to call a function anywhere and get the current media query context allowing for amazingly intelligent mixins and functions to be written in Sass, something unique to Breakpoint that you simply don't have with interpolating variables.

IB: Are there any responsive web design aspects specific to Drupal theming/frontend development that Breakpoint helps with?

SR: There is nothing Drupal specific that Breakpoint helps with. Breakpoint, like Sass, was built to be backend independent. This means that if you are building any site, regardless of if it's a Drupal site or a Node site or a static site, Breakpoint is able to do its job handily without being caught up in being tied to a specific backend technology.

MW: One of the things I love about working with Sass is that it's not Drupal-specific, and it's meant to be used anywhere on the web. Breakpoint follows that example.

IB: Is Breakpoint a successor to Respond-To, or will that continue to get developed?

SR: In a way, yes and no. Respond-To was written before Breakpoint, but upon Breakpoint's release, it was decided that our efforts should be focused on a unified Media Query engine, with Respond-To as a wrapper syntax for Breakpoint. This is how the current Respond-To project exists. As of Breakpoint 2.0, the Respond-To mixin has been incorporated into Breakpoint core, so you now can use Respond-To without needing an additional Compass extension!

IB: Do you use Breakpoints module (in Drupal 8 core)? Or do you just do all of that through Sass?

SR: I personally truly dislike the Breakpoint module. Every use case I've heard for it seems to be based on the thinking that sites have three or four breakpoints and that everything can be boiled down into an easy to use admin interface. There are no standard breakpoints, period, and good, reasonably complex responsive sites will usually have 20 or more breakpoints. Responsive cannot be done from the backend, and the Breakpoint module encourages you to do so (as does the Spark layout initiative).

IB: Do you think any aspects of Breakpoint might get rolled directly into Sass in the future?

MW: It's possible, but we probably won't move the obvious parts to the Sass language. There are some helper functions that we've written in Ruby that would be very useful in Sass core. Once that's in we'll be able to offer Breakpoint without Compass.

SR: I do not believe Breakpoint will be rolled directly into Sass, nor would I want it to be, as it is out of scope of Sass core. As much as I like them, I even think the color functions in Sass are out of scope for it. Sass core should simply be the language and the bare minimum function base for it to be useable. Sass doesn't ship with any mixins, and I think it should probably stay that way. That being said, Breakpoint is fairly stable; our 1.3 release stood stable for six or so months without needing any changes until we rewrote the whole thing for our 2.x release, so maybe being merged into Compass isn't out of the question, but I do not see a need for that.

IB: I hear in addition to Breakpoint, Sam went and created some kind of magic box of Sass called Toolkit. Want to say more about that?

SR: Toolkit started life as RWD Kickstart, a project Mason and I kind of made up on the spot a year ago at one of the first New York Sass meetups. Its original goal was simply to be a collection of Compass templates to make pulling in media query and grid solutions together easily. Since then, it's evolved to be more of a collection of Progressive Enhancement, Design in Browser, and Modern Web Development tools, a toolkit if you'll let me, of useful tools. I'd say the four biggest thing that Toolkit has are a modern Clearfix mixin, progressive enhancement replace text mixins, a triangle generation mixin, and an intrinsic ratio mixin to make using intrinsic ratios super easy. It also adds *, *:before, *:after { box-sizing: border-box} and img, video { max-width: 100%; height: auto; } to your stylesheets, which are the first two things I do for any responsive project.

SR: Toolkit's templates have also evolved, Where originally there were five some odd different templates to choose from, now there are just two, a basic one to set up a basic partial structure, and a responsive web design one that pulls in Breakpoint 2.x for media queries and Singularity 1.x for grids.

IB: You sure know those late twentieth-century presidents.

MW: With a name like Breakpoint, how could I not revisit the cinema classic Point Break. Bodhi and his gang of thrill-seeking bank-robbing surfers evaded the FBI for years until the newly minted Special Agent Johnny Utah was on the case. I think we can all agree that there's a poignant metaphor for web designer there. And some pretty sweet gifs.

Join Rootwork on Twitter, Facebook and SlideShare.

Learn about Rootwork's services for nonprofits and social change.

May 15 2013
May 15
Screenshot from Dale's presentation: When designers change colors on CSS

It's fair to say that in the last year, adopting the CSS preprocessor SASS has completely changed frontend development for me. That's a sentiment I've heard others express when they started using it — and I was pretty late to the party.

I got attracted to it initially through variables. We've all been there when a client or a designer wants to change a color and suddenly we have to change dozens or hundreds of values across CSS.

Dale Sande captures that kind of revolution in efficiency that SASS brings, as seen in a screenshot from his upcoming presentation at Drupalcon Portland.

But Dale, who's spoken plenty on SASS and organizes the Seattle SASS meetup, is taking us way past the SASS basics like variables, and that's why I'm excited to see his presentation next week.

Around the same time SASS came onto the scene, some thoughtful people were exploring more maintainable frontend development and CSS architecture through ideas/acronyms like OOCSS, SMACSS and BEM, and folks like Nicole Sullivan, Jonathan Snook (a Drupalcon featured speaker!), Nicolas Gallagher, and Harry Roberts.

I spoke with Dale about SASS, object-oriented CSS and some the things he'll be covering at Drupalcon. Be sure to join me at his session, "Sass: OO'S'CSS w/Extends and Silent Placeholders," on Wednesday at 2:15 PM!

IB: Some people argue SASS creates bloated code — do you see placeholders addressing that concern effectively?

DS: Sass doesn’t create bad code. Bad coders do.

The whole concept of placeholder selectors was designed to fight code bloat and be a more pragmatic solution to OOCSS. In my presentation, I illustrate how using the various techniques generate code.

The real "ah-ha" moment comes when we see how using placeholder selectors makes it easier to manage and literally re-use code — thus reducing dreaded CSS bloat.

IB: What's the advantage to using silent placeholders over mixins for a set of rules?

DS: Simply put, being able to re-use code without duplicating code. The use of mixins was the first part of being DRY with our code. Looking at the Sass it felt AWESOME! But when we looked at the output CSS, this is when we realized that we were all living a lie.

Our CSS rules were being duplicated tens, if not hundreds of times. We weren't being DRY, we simply put the onus of duplication on the machine.

Placeholder selectors embrace the one of the oldest concepts of CSS and that is to extend the CSS selector for reuse. But with traditional CSS this was difficult to do, especially when you were dealing with thousands of lines of code. Sass' @extend directive allows developers to create name-spaced reusable chunks of code that is portable, re-usable and extendable without duplicating anything.

Fighting tight coupling in CSS by keeping code separation in SASSIB: Do you see placeholders as helping to reduce the amount of tight coupling — scattering pieces of styles in multiple places?

DS: While Placeholder Selectors are a tool that can help with scattered code, it is not the only solution. Having a file/folder structure that embraces the different types of code, e.g. CSS selectors, placeholder selectors, mixins and functions, can assist in creating reusable modulare code and maintain a process of control over the many parts.

Images: Screenshot from Dale Sande's presentation.

Join Rootwork on Twitter, Facebook and SlideShare.

Learn about Rootwork's services for nonprofits and social change.

May 14 2013
May 14

Jack, my co-themer here at Advomatic, and I will be doing a series of articles about how we use SASS and Compass on our projects. There are plenty of articles out there on what it is and how to get started, so we wanted to dig a little deeper, and share a few tips and ideas.

is that IE7 I smell?

Today I'll talk about Modernizr, which is a javascript library that will check to see if your browser supports HTML5 and CSS3 features. We use it on every project now to make sure we aren't serving unsupported stuff to browsers that can't handle it. One thing Modernizr does is add classes to your HTML tag, like "cssgradients" or "no-cssgradients," or "textshadow" or "no-textshadow" as the case may be. Combined with SASS, this can be a very simple way to limit your CSS3 work. Here's an example of how we now apply any of our css3 theming, using the way SASS allows you to check for parent classes, and the nice CSS3 includes of Compass.

h1.title {  // A double border, for browsers that support box shadows; single border for those that don't.
  border-bottom: 1px solid #c3c3bf;
  .boxshadow & {
    @include box-shadow($white 0 1px);
  }
}

Here's a slightly more elaborate example:

#footer {
  background-color #114163: // a baseline background color
  .lt-ie10 & { // dirty proprietary filter for IE9 and below
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#2074b1', endColorstr='#114163');
  }
  .cssgradients & { // gradient for CSS3-supporting browsers
    @include background-image(linear-gradient(#2074b1, #114163));
  }
}

By the way, that handy ".lt-ie10" class on the html tag is standard now in Drupal's Zen base theme. It's very handy. While we try to avoid it, we also will add in classes for .mac, .pc, .chrome, .firefox and .safari, if we have some extremely browser-specific problems, which is rare. If you are curious, here's the javascript we use to add that information to the html tag.

Drupal.behaviors.targetBrowsersOS = {
  attach: function (context, settings) {
    // Check to see which operating system we're using.
    if (navigator.appVersion.indexOf("Mac")!=-1) {
      $('html').addClass('mac');
    }
    else {
      $('html').addClass('pc');
    }
    // Check to see if the browser is Safari and doublecheck that it is not Chrome.
    if (navigator.userAgent.indexOf('Chrome') > -1) {
      $('html').addClass('chrome');
    }
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
      $('html').addClass('safari');
    }
    if (navigator.userAgent.indexOf('Firefox') > -1) {
      $('html').addClass('firefox');
    }
    if (navigator.userAgent.indexOf('MSIE') > -1) {
      $('html').addClass('ie');
    }
  }
}

So, as you can imagine, this gives you the ability to customize what css various browsers are served, and leaner, cleaner experience all around. Stay tuned for more SASS/Compass tips and tricks!

May 10 2013
May 10
Responsive & adaptive grids with Susy, Sass & Compass in Drupal 7

Here at Advomatic we've experimented with several approaches to responsive design over the past few years. I think the "mobile first" philosophy became popular right in the nick of time. There was a point when we'd detect if the user was on a mobile device and then deliver a separate mobile theme. This meant two instances of a site to develop for and maintain. I can't imagine doing that now, given the amount of device width/height possibilities and device-specific bugs that exist out there. So, now we work on layout with the goal of accommodating the content rather than the device. To accommodate a responsive and flexible layout, it's best to get your site on a grid. There are tons of options out there, but we've found one in particular helps you quickly get rolling and set up with a column layout that can adjust to whatever device you need your site to display on (and is fun to work with, too). Lately, it's been part of our holy trinity for responsive theming: Sass, Compass and Susy.

First things first: ditch pixels

One big first step to responsiveness in your site is to stop using pixel units for measurements. We use em units because they are proportional to any parent measurement, and therefore flexible and responsive. If we have a base font-size set on the body element of 16px, and our #footer is set to 1.6em, that #footer font-size will automatically scale up or down accordingly if the body's (or any parent element to #footer, for that matter) font-size changes. To manually figure out exactly what em value you should be using for an element, you can use a commonly used formula: target ÷ context = result... or you could do it the easy way with a Sass function:

// Create em() for setting font-sizes in pixels.
@function em($target, $context: $base-font-size) {
   @if $target == 0 { @return 0 }
   @return $target / $context + 0em;
}

// Example usage: font-size: em(21px);
// This will set the font-size to 21px in relation to the browser's base font size if it has not been established in any parent element, or in relation to $base-font-size which is a variable you can set in your Sass.

// Example usage 2: font-size: em(12px, 10px);
// This will set the font-size to 12px in relation to a parent element's font-size of 10px.

Get on the grid

If you're doing front end development these days, you're probably familiar with the concept of grid-based design and translating a comp into a fully fluid or adaptive layout via HTML/CSS. We frequently use Zen 5 as a base theme and have been big fans over the years because it comes loaded with many of the best tools for front end/theme development, while also pretty lean as far as bloat goes. While it's important to be able to build themes for browsers that can handle fancy bells and whistles, we also need to support older browsers that don't. Zen 5 already has Sass and Compass integrated. As far as a grid framework goes, we use Susy instead of Zen Grids... this has just come down to personal preference. Zen Grids is also a great system. Susy is a responsive grid framework/plugin for Compass, and it allows you to build on top of either a "magic", static or completely fluid grid.

  • "Magic" grids are the default - they have an elastic container that responds to font sizes when set with em units, and is fluid on the inside. It's container size gets calculated according to the widths of your columns and gutters.
  • Static grids are just that - all containers and column widths are not flexible and this is the traditional grid style. As such, it does not collapse when the viewport is smaller than the grid is wide. Even though you may specify pixel values for the column sizes, Susy converts to a percentage of the container size. The container size, like the magic grid, gets calculated according to the widths of your columns and gutters.
  • Fluid grids are truly flexible layouts that respond to the width of the viewport. By default the container width is 100%. However, as with any grid type you choose, you can specify this with the $container-width variable (such as "$container-width: 70%").

Set it all up

To add Susy to your theme, there are a few things you'll need to do.

  1. If you haven't already, install Sass and Compass.

    sudo apt-get install rubygems
    sudo gem update
    sudo gem install sass

    sudo gem install compass

  2. Set up a Compass project in your theme directory.

    This is already done for you with Zen 5. If you're not using Zen 5 or a contrib theme that has this done already (look for a config.rb file in the theme directory), then set up your Compass project by going to your theme directory in your favorite command line interface and run:

    compass create nameofyourtheme

    This will add a "config.rb" file to your theme, and is where the Compass project settings are located.

  3. Then, install Susy.

    sudo gem install susy

  4. Require Susy in your Compass project.

    Open up the config.rb file and add the following (wherever "requires" are located):

    require "susy"

  5. @include susy and add grid settings to your _base.scss (or equivalent "global" Sass file).

    We usually stick any of our grid settings in the _base.scss file that comes with Zen so that the grid variables set there are available to any other Sass stylesheet in the theme (because Zen's base gets @imported in them all). You'll also want to place them in whatever Sass file you're using that gets imported into any file where you'll be doing responsive styling/layout. For example:

    @import "susy";
    $total-columns: 12;             // a 12-column grid
    $column-width: 4em;            // each column is 4em wide
    $gutter-width: 1em;            // 1em gutters between columns
    $grid-padding: $gutter-width;  // grid-padding equal to gutters

After installing Susy, and getting your Compass project set up properly for the theme, you'll want to tweak those default grid settings that you just added (total columns, column width, grid padding, etc...) for the purpose of your own design. Using those settings, Susy will automatically figure out the math and put percentage widths on internal grid elements, as well as a max-width on the container (should you use a non-fluid grid). By default, all Susy grids are "magic." If you want to use one of the other types of grids, you would do that by setting the $container-style variable. For example, to build a 5 column-wide mobile first "magic" layout, we can do something like this:

$total-columns: 5;
$column-width: 3em;
$gutter-width: .75em;
$grid-padding: $gutter-width;

Making things happen at different viewport sizes

Another handy part of Susy is its at-breakpoint() mixin. This can be used in replacement of a long and drawn out media query that targets specific pixel-based min-width or max-width values of the viewport. Something we do frequently for adaptive/responsive layouts (where there are established, comp-determined breakpoints for mobile, tablet, desktop), is set variables for different numbers of grid columns.

$mobile   : 5;
$tablet   : 11;
$desktop  : 16;

So if you're building in a mobile first manner like this, and you want something to happen at a certain breakpoint in your Sass, you can use at-breakpoint() with your column count variables as an argument.

#content {
  @include span-columns(5);
  @include at-breakpoint($desktop) {
    @include span-columns(13, $desktop);
    @include prefix(3, $desktop);
  }
}

In this situation, #content normally spans 5 columns wide, which is the default/mobile width of the grid in this example. When the viewport is at the desktop breakpoint (16 columns can fit in the viewport), the width of #content will change. span-columns(13, $desktop) means "make this 13 columns wide, out of 16 total columns". prefix(3, $desktop) means "add 3 columns of empty space beforehand." So #content becomes 16 columns wide in total, however only 13 columns of space are usable and contain content, since we added 3 columns of padding to the start. A different, non-layout related way of using at-breakpoint() is to maybe change some kind of style at a given breakpoint.

padding-bottom: em(15px);
@include at-breakpoint($desktop) {
  padding-bottom: em(85px);
  background: url("bg-content.png") 162px 100% no-repeat;
}

Having at-breakpoint() at the ready is a great way of releasing yourself of the mindset and clutter of maintaining several pixel-based breakpoints in your site, and helps future-proof things since device sizes are fluctuating so wildly as time goes on. Since Sass supports code nesting, it has become standard operating procedure for us to use at-breakpoint() at the end of things in a selector's nested styles, so that they override any established defaults (which are usually the mobile version styles if we are building mobile-first).

Alternatively, Aurora

While we normally use Zen and add Susy in manually (replacing Zen Grids), some themes have Susy, Sass and Compass (and other front end goodies) baked in already. Aurora is also a Sass & Compass-powered minimalist theme with a focus on best practices for HTML5 and front end development within Drupal. It has a number of cool features like Google Chrome Frame and Typekit integration. Aurora encourages the use of Panels' HTML5 Sections layout instead of using the standard Drupal left/right sidebar block regions for sidebars. Aurora also suggests you use the Blockify module to turn all the little things on the page that normally get rendered in a page template variable into blocks that you can assign to regions via Drupal's block admin page. There are a number of features in Aurora which have been pulled out and put into a separate module, so that any theme can make use of them. That module is called Magic and some of it's best features are the ability to exclude certain CSS/JS from being included, exporting of theme settings, enhancement of CSS aggregation and adding a viewport width indicator - which is very helpful when developing a responsive site to check all your breakpoints and everything in between.

Conclusion

Susy provides a great way of quickly getting your site layout blocked out and can produce any kind of grid you need. What has your experience been like using Susy in Drupal?

Mar 12 2013
Mar 12

*Sorry, but this will require using the command line.

I think at this point it is pretty obvious that I prefer a GUI over the terminal any chance I can get. That is why CodeKit and I were made for each other. I have just recently jumped on the Sass bandwagon/trend and am trying to learn all the tools that go with it. So of course when I found Sass, I also found Compass. The last thing I wanted to do was install these via the terminal. I use a Mac, and while I saw that it was very minimal to do this with the command line and Ruby gems, simple it may be, it was still against my principals none the less. This is where CodeKit came into play. Woot! I now easily had Sass, Compass, and a watched project, all using my best friend — the mouse.

Then came along Zen Grids, a Sass-based responsive grid system. This was something I wanted to learn and take advantage of in our theming work. Looking at the Zen Grids site it said it was as simple as:

gem install zen-grids

This is, of course, assuming you have Sass and Compass already installed. And I thought to myself "Of course I have those installed. I'm using it right now." Well, not so fast. CodeKit runs its own self-contained internal version of these Ruby gems. Although these main gems (Sass and Compass) are no different than the regular ones, having them inside of CodeKit's own little universe makes things a bit more complex when using even more 3rd party gems with Sass. I found this out after I ran this simple command (insert apology here) because I could find no other way to install it. The command ran smoothly and I was excited to think I had Zen Grids installed and ready to go.

I opened up my Compass project and edited the config.rb file as Zen Grids requires you add this to it:

require 'zen-grids'

Simple enough, then just include this in your .scss file:

@import "zen";

Now I can start building grids like nobody's business! That was until I hit save and got a dreaded ".scss did not compile" error from CodeKit. So what do you do now? The obvious, Google the problem. These are the articles that got me to figure out my solution but none of them solved it exactly as it did for each writer:

    The first link is what made me realize this is an issue and not just me, but the first command he recommended running did not work for me, so I continued on with my searching. The second article made me understand the fact that CodeKit runs on internal installs of Sass and Compass and that was more then likely my issue. That article points to an image that shows where to configure the paths for Sass in CodeKit (under Preferences > Languages > Sass), and how to point it to a version of Sass installed via command line, which I avoided since I am using CodeKit, and wanted to avoid the command line in the first place.

    CodeKit

    Now I noticed a few other sites that pointed this out and all of them pointed to /usr/bin/sass which was a path I had on my system. So I changed it to that and tried again to create some grids, but I found that I was still getting errors when compiling the .scss file. After quitting apps, refreshing apps, pulling out my hair, I went back to Google. It was the third link that showed me a different path for the installation of Sass. I navigated to that path and found Sass and Zen Grids there. So I pointed CodeKit to that but was still getting errors. I decided to break down and install Sass and Compass yet one more time, this time with the command line, using these commands:


    gem install sass
    gem install compass

    After what appeared to be a successfull installation I tried one more time to compile my .scss file. Argggggg! I took a look around and found that you can also point CodeKit to an external Compass install and luckily I knew right where that was (on the same Preferences > Languages, under Compass).

    CodeKit

    Now that I had this in place I compiled one more time and finally everything was working and I was on my way to creating some Zen Grids. I have no idea what these paths are all about and why some are different. Perhaps it is due to different Mac OS versions or different users on the Mac. All I know is that I now have Zen Grids working and I can still use CodeKit to create Compass projects, have them watched, reload, and working like a champ.

    Feb 01 2012
    Feb 01

    Right now everyone wants a good mobile experience for their site and that is sparking discussions about what theme you can and should use to make your site accessible to the mobile world. At Zivtech, we feel that we have outgrown starter themes because we spend more time overriding than using them (especially in D7 since a lot of the great Zen stuff is baked right in). The other day I got to thinking, just what would it take to build a responsive theme for Drupal from scratch. Is it so complicated that we need systems upon systems to handle it?

    You probably guessed, my answer is no. It turns out it takes less than fifty lines of code to build a basic working responsive theme complete with media query powered break points. If a completely custom and highly flexible layout can be made in less code than zen’s opening page.tpl.php comment, why use a base theme for responsiveness? Of course, I cheated a little by using an amazing framework that a coworker and zealot turned me onto awhile back called Susy.

    Susy

    Grid systems have been around for quite a few years now but the advent of Sass makes them a whole new ball game. Until CSS preprocessors, working with a grid system (like blueprint or 960.gs) meant you included some boilerplate CSS files that gave you a bunch of nice default grid behaviors. Then you just had to take their selectors and add them to your markup. This works well and it is very cool, the one problem is it is not semantic. You are changing your doc to change your presentation, yeah it’s necessary but really not cool and what that ol’ zen garden was all about avoiding. Enter Sass.

    Sass is all about making CSS as terse as humanly possible, so a major feature is having simple functions that you can pass variables to (called mixins) for generating all of your CSS quickly and easily. This means you can leave your markup alone (especially in Drupal where everything and its mother is a div with 10 classes) and you can generate tailored grid CSS to match. No presentation leaking into our DOM (at least until we start hitting edge cases).

    Introducing Tony

    Following the Drupal 7 core’s own Stark theme for guidance, I created nothing more than an .info file and a layout.css, giving me an installable theme called Tony (named for my favorite Stark (sorry, that one was for the nerds)). My goal with Tony was to create a bare bones Drupal 7 theme with a fully functional responsive layout built with media query based break points to keep the layout friendly to displays of all sizes (including mobile). Experimenting with Tony requires that you have Compass and Susy installed on your machine.

    You can always find Tony in my sandbox if you want to toy around with it, though I really don’t intend to turn it into a real base theme. Remember, we have a lot of choices there and it’s what I’m trying to avoid.

    Step by step

    Now lets take a tour of the code:

    @import "susy"

    This line just imports compass and Susy.

    $total-cols: 8
    $col-width: 50px
    $gutter: 8px
    $gutter-width: $gutter
    $side-gutter-width: $gutter-width

    Here’s where the magic begins. Here we set the stage by establishing the number of columns in our grid, the width of each one, the space between each element (the gutter) and how much room we should have on the far left and right sides. These global variables will be used by Susy everywhere else to determine what CSS it should generate. Note that we are free to enter our dimensions in pixels but Susy will do all the hard math to convert these into % ratios so that our layout can respond proportionally to the size of the screen.

    @mixin full-width
      +columns($total-cols)
      +alpha

    If you’re not familiar with Sass’s syntax you’re in for a treat and I highly recommend you read up. You’ll thank me. What this does is define a mixin that can be used throughout my css to reapply a few lines of code. This one sets the width of an element by proscribing it the appropriate number of columns (in this case all of them) and then applies the alpha styles (as opposed to omega) telling Susy we want this to go to the left. The first element in a row should always be an alpha and the last one an omega.

    #page-wrapper
      +container
      +susy-grid-background()
      width: auto
      margin: 6em
    #header, #navigation
      @include full-width
    #sidebar-second
      +columns(2)
      +omega
    #sidebar-first
      +columns(2)
      +alpha
    #content
      +columns(6)

    Here we set the stage. Again, borrowing from Stark, this theme uses Drupal 7’s stock markup without any tweaks. We apply one of Susy’s mixins with +container to turn the #page-wrapper div into a container, applying the global Sass variables we created before by calling Susy’s +container mixin. We then turn on a visible grid to show our grid as a reference (obviously just for the design/development phase). Next, we set the width to auto so that the page will grow to fill any screen size and set all margins to 6em to give it a bit of breathing room and space for a background. We also set widths for the sidebars by calling the Susy mixin (again, like a function for generating CSS) and passing in an argument of the number of columns this div should take up. Note we set whether the sidebars should appear first and last by calling +alpha and +omega Susy mixins as well. You can read more about how this works here. Finally we set the main content region’s width at 6 columns (the default appropriate to both left sidebar only and right sidebar only).

    body.one-sidebar.sidebar-first #content
      +omega
    body.one-sidebar.sidebar-second #content
      +alpha

    These four lines set #content to float right or left based on which side bar is currently visible.

    body.two-sidebars
      #content
        +columns(4)
      #sidebar-first
        +alpha
      #sidebar-second
        +omega

    Here we set the content to float in between the sidebars and adjust it’s width to accommodate having an extra sidebar. The grid system makes the math easy, 8 columns - (2x 2 sidebars) = 4 columns. That’s it, now we have a fluid grid based layout that can accommodate all of our side bar variations. A great start, but I did promise to make this responsive, so now the real fun begins:

    Media Queries

    Media queries allow you style sheets to apply specific styles depending on the current size of the browser. Normally these need to go a the root of your CSS document but thankfully Sass has a media bubbling behavior that will ensure they find their way to where they belong and you are free to define them in a place that makes sense to you, even nesting them inside other selectors.

    @media screen and (max-width: 1000px)
      #page-wrapper
        margin: 1em
          top: 0

    Here we specify that if the browser width ever dips below 1,000 pixels, we should remove the top margin, drop the rest of the margins from 5em to 1 and stop using up so much real estate for borders. This helps on smaller screens and netbooks, but to be able to work well all the way down to mobile, we probably want to kill our margins completely and pop the sidebars above or below our main content.

    @media screen and (max-width: 500px)
      #page-wrapper
        margin: 0
      body.one-sidebar.sidebar-first, body.one-sidebar.sidebar-second, body.two-sidebars
        #content, #sidebar-second, #sidebar-first
          @include full-width

    And that’s it! We covered all the big ticket items in less than fifty lines of code (at least, before compiling). So if the responsive grid system and media query break points can be achieved reliably and easily without tedious calculations, tweaking or templating… Why use a base theme at all? A good mobile experience needs to be hand tweaked, that’s easier to do if you have a full control and understanding of what’s going on. We all need to change how we think about presentation and I don't think any theme out of the box will be a good mobile experience for your content.

    Now all you have to do is make it look good, but that’s really a whole other post.

    Mar 12 2009
    Mar 12

    SASS HAML

    Over the past couple of months, my interests have peaked in the land Ruby on Rails in particular SASS (Syntactically Awesome StyleSheets) which is apart of the RubyGem plugin, HAML. This was initially introduced to me while working on a project for Raincity Studios and the brilliant developers at OpenBand Labs by lead designer and front-end developer, Alex Bendiken.

    SASS (Syntactically Awesome StyleSheets) is a meta-language on top of CSS that‘s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.

    Features

    • Whitespace active
    • Well-formatted output
    • Elegant input
    • Feature-rich

    Examples of SASS

    Similar to flat CSS, selecting elements are done by the elements ID and or class name(s). Here is an example of SASS written with nested rules.

     
    #main p
        :color #00ff00
        :width 97%    .redbox
          :background-color #ff0000
          :color #000000

    Compiles to:

      #main p {
        color: #00ff00;
        width: 97%; }
        #main p .redbox {
          background-color: #ff0000;
          color: #000000; }

    For additional documentation on SASS, please visit The SASS Homepage.

    Benefits to using SASS

    I've had the privilege of working with a bunch of projects already using SASS and have been thoroughly amazed at how fast and efficient it is at maintaining a consistent code structure and providing organized code, which is often difficult to do in a collaborative environment when working on client projects.

    Modularization of code is also a benefit to this framework. Being able to plug in various "pre-made" styles allows themers to share snippets while maintaining hierarchal syntax awesomeness.

    Starting with Drupal

    Currently there are 2 Drupal projects, maintained by myself, which focus on development with SASS on Drupal.

    • Basic boasts a clean HTML structure with extensible CSS classes and ID's for unlimited theming possibilities as well as a top-down load order for improved SEO. This version includes SASS ready files for instant development on Drupal. This theme is intended to be used with the SASS API module.

    • The SASS API allows themers to automatically compile their SASS files into flat CSS files to be rendered for the visiting user. SASS files can either be compiled in real-time or during cron run.

    Notes

    • SASS requires the HAML RubyGem plugin to be installed. Mac OSX Leopard has native support for SASS (otherwise run $: gem install haml)
    • For installation instructions on installing Ruby/Haml on Mac OSX Tiger, please read: Building Ruby, Rails, LightTPD, and MySQL on Tiger

    About Drupal Sun

    Drupal Sun is an Evolving Web project. It allows you to:

    • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
    • Facet based on tags, author, or feed
    • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
    • View the entire article text inline, or in the context of the site where it was created

    See the blog post at Evolving Web

    Evolving Web