The humble SASS $variable
Consistency and continuity without really trying
SASS is an extremely powerful and flexible language that enables us to work quicker and smarter to generate CSS. For me, one of it's most useful features is one that almost seems to be taken for granted, the simple $variable. With a little consideration about how we define variables, we can ensure a subtle but important consistency throughout pages and across breakpoints, whilst retaining the flexibility we need to Get The Job Done ™
This site makes extensive use of SASS variables for all aspects of layout and typography. There is a super simple proportional layout system that I'll write about another time, but that importantly generates variables $column
and $gutter
Padding and offsetting with $column
and $gutter
$gutter
is currently set to 20px. By setting padding:$gutter/2;
and padding:$gutter/4;
throughout the SASS files, I know I'll have consistent padding across all elements that require it. Similarily, by using $column
, $column/2
or $column/4
to offset elements, I get margins that are always proportional and consistent.
Media queries with $break-point
The basic grid has a max-width
set using variable $page-width:960px;
. This is used this to generate some basic breakpoints:
$sml-breakpoint:$page-width/3;
$med-breakpoint:$page-width/2;
$big-breakpoint:($page-width/3)*2;
Using these as the basic breakpoints in @media
queries ensures the page responds predictably at any given screen size — I don't need to remember whether I previously set max-width:320px
or min-width:321px
.
Combining these breakpoint variables with $gutter
and $column
gives a powerful way to generate layouts across a range of screen sizes that can be implemented with minimal effort whilst maintaining consistent proportion.
A simple example
An example of the techniques described above can be seen on this very page. When the browser viewport is greater than 960 pixels (as defined by the $full-width
variable), the main and sub– headers are offset using:
margin-left:-$column;
The post meta data, showing the publish date and author information, also has a horizontal margin set to the value of -$column;
, and additional horizontal padding set as the value of $column/2
to push the date element back inwards. This gives a pleasing diagonal rhythm that leads the eye in to the introductory paragraph.
As the available screen size decreases*, the margins and padding change appropriately to be fractions of the $column
and $gutter
, therefore maintaining the relationship and rhythm between the elements whilst maximising the use of the screen.
* Technically, the changes happen as the screen size increases, not decreases, in a mobile–first fashion.