Getting Began with Sass – A Record Aside

CSS’ simplicity has at all times been considered one of its defining, most welcome options. CSS fashion sheets are simply lengthy lists of guidelines, every consisting of a selector and a few types to use. However as our web sites and purposes get larger and turn out to be extra complicated, and goal a wider vary of units and display screen sizes, this simplicity—so welcome as we first began to maneuver away from font tags and table-based layouts—has turn out to be a legal responsibility.

Article Continues Under

Whereas some have supplied proposals on methods to repair CSS—including constants or variables, for instance—none have been applied by any browser producers. And even when a browser did implement a more moderen, higher, prolonged CSS, it might be years earlier than the brand new syntax is supported nicely sufficient in all browsers for it to make sense to make use of it.

Fortuitously, a number of years in the past builders Hampton Catlin and Nathan Weizenbaum proposed a greater technique to keep an advanced stylesheet. Whereas browsers aren’t prepared for a brand new CSS, Catlin and Weizenbaum realized they may go forward and design a brand new fashion sheet syntax with options to assist make their more and more complicated CSS simpler to jot down and handle, then use a preprocessor (a program that runs in your pc or server) to translate the brand new sensible syntax into the previous, dumb CSS that browsers perceive.

The brand new stylesheet syntax they developed known as Sass, which stands for “syntactically superior fashion sheets.” The unique variations of Sass regarded very totally different from common CSS; there have been no curly braces, and properties needed to be indented with a particular variety of areas or else the compiler would increase an error. Programmers (who’re used to studying new syntaxes, and revel in ache) didn’t thoughts this a lot, however for normal net designers it was totally different sufficient from the CSS they knew that the majority of them stayed away. There was a sensible situation as nicely: as a result of Sass’ indented syntax wasn’t suitable with common CSS, it was troublesome for folks with giant current web sites to start out benefiting from it with out spending time changing their previous code to Sass.

So in Sass 3.0 the builders launched a brand new, extra CSS-like syntax referred to as SCSS (or “Sassy CSS”). SCSS is what the nerds name a “strict superset” or “metalanguage” of normal CSS, which suggests something that’s legitimate CSS can be legitimate SCSS. In different phrases, all your current fashion sheets ought to work with the Sass processor with no issues, permitting you to get your ft moist by taking part in with some Sass options with out studying each aspect of the brand new language.

In contrast to common CSS, Sass’ SCSS is an actual scripting language, with expressions, capabilities, variables, conditional logic, and loops. You don’t have to make use of all of those options to get some profit out of Sass, however they’re there for those who want them, and on giant tasks they will make complicated or repetitive CSS a lot simpler to jot down.

For this text I’m going to reveal a number of primary strikes, to offer you an thought of what’s doable with Sass and SCSS in your designer’s utility belt. On the finish I’ll advocate some hyperlinks and books to take a look at while you’re able to discover additional.

To maintain issues as clear and easy as doable, most of my examples under focus simply on the SCSS code, not the compiled CSS output. The easiest way to grasp how Sass works is to strive it for your self, by writing some SCSS types and seeing what comes out. That mentioned, all of my supply code examples can be found on GitHub in your reference, together with their compiled CSS output, so you’ll be able to see how all of those neat new options translate into usable fashion sheets.

Sass is written in Ruby, and distributed by way of the Ruby package deal supervisor, RubyGems. In the event you’re already conversant in Ruby (and your pc’s command immediate) you could find directions for putting in and working the Sass gem on the Sass web site.

For individuals who are much less useful on the command line, or who simply desire a quick and straightforward technique to work with Sass, there’s Scout, an AIR app out there for Mac and Home windows that comes with Ruby and has the Sass compiler inbuilt.

Each the sass command line device and the Scout app work by watching your SCSS fashion sheets for adjustments as you’re employed on them, then routinely compiling them into common CSS while you save. The listing the place your Sass recordsdata reside known as the enter folder. Your processed CSS recordsdata are saved to the output folder. These folders might be nested inside each other; the truth is, a typical sample is for the enter folder (which I normally name “scss,” although you’ll be able to title it no matter you want) to reside within your web site’s common stylesheets folder, like so:

my_project/
  index.html
  css/
    main_style.css
    scss/
      main_style.scss 
      _mixins.scss
      _colors.scss

In my scss folder above, the recordsdata whose names begin with underscores are referred to as partials. Because the title would indicate they include “partial” fashion sheets, chunks of SCSS code to be imported into considered one of your most important SCSS recordsdata. I’ll speak extra about partials in a second, however now the place they reside.

Use partials to arrange your code#section3

CSS already gives the @import directive for linking to further, exterior fashion sheets, and a few builders like to make use of it to interrupt up a big venture’s types into smaller logical chunks. For instance, our main_style.css file may include nothing however @import statements linking to a bunch of page-specific fashion sheets:

@import url('/shared/international.css');
@import url('/pages/house.css');
@import url('/pages/weblog.css');

This isn’t thought-about the very best apply nevertheless, as a result of every of those imports is another file that must be requested and loaded by the browser, which might make your web site load extra slowly and will certainly decrease your YSlow and Google Web page Pace scores.

Sass helps out by letting you break giant fashion sheets into partials. You continue to seek advice from them utilizing the @import directive (in a brand new, briefer type), and when your SCSS recordsdata are processed, the contents of the partial are inserted immediately into the output CSS. (Importing a URL works the identical manner it does in common CSS.)

@import 'shared/international';
@import 'pages/house';
@import 'pages/weblog';

The result’s one file containing all your types. Sass also can routinely minify its CSS output, stripping out pointless white area or line breaks to optimize loading instances.

There’s one catch. Partials are a particular sort of SCSS file, not meant for use as common stylesheets. Any code you set into one should be @import-ed right into a stylesheet for use. Partials’ filenames should begin with an underscore—for instance, the pages/house partial loaded above would truly be named pages/_home.scss. (These paths are at all times relative to the present file.) The underscore is how the Sass compiler is aware of {that a} file is a partial, and due to this fact shouldn’t be compiled right into a fully-fledged CSS sheet. However given the aim of a partial is to arrange your code into logical chunks, this appears a good trade-off.

Don’t repeat your self#section4

Now that our fashion sheets are higher organized, let’s attempt to make them much less repetitive.

One in every of Sass’s nicest options is nested guidelines. In an everyday CSS file, guidelines have to be listed sequentially, and each rule’s selector should embrace all of its components:

physique.house .media-unit {
  border: 1px strong #ccc;
  background-color: #fff;
}
physique.house  .media-unit .proper {
  border-left: 1px strong #ccc;
}
physique.house .media-unit .proper h1 {
  font-size: 24px;
}

Aside from being actually, actually repetitive, this code doesn’t do something to assist us perceive how the HTML components we’re styling relate to one another. With nesting, we are able to write SCSS code that’s each much less redundant and simpler to comply with:

physique.house {
  .media-unit {
    border: 1px strong #ccc;
    background-color: #fff;
    .proper {
      border-left: 1px strong #ccc;
      h1 {
        font-size: 24px;
      }
    }
  }
}

After processing it will lead to the identical CSS as above. Sadly, the shorter syntax received’t make your CSS recordsdata any smaller or load any quicker. However nesting will assist preserve your code clear, logical, and well-organized, which also needs to make it simpler to handle over time.

One other cool nesting trick: Sass means that you can nest media queries inside different guidelines, making it simpler to see which types are utilized to a given object in your web page:

.container {
  width: 940px;  // If the machine is narrower than 940px, swap to 
  // a fluid structure
  @media display screen and (max-width:940px) {
    width: auto;
  }
}

When processing this file, Sass is aware of methods to convert this again into legitimate CSS, copying the .container selector contained in the media question like so:

.container {
  width: 940px;
}@media display screen and (max-width:940px) {
  .container {
    width: auto;
  }
}

Variables#section5

Sass variables are nice for 2 causes. First, and most significantly, they make code simpler to alter by lowering duplication. However additionally they mean you can assign names to particular property values like colours, which helps you perceive the intent behind a given fashion.

At Typekit numerous components in our UI use our signature inexperienced coloration, #99cc00, or “Typekit inexperienced” for brief. This coloration seems a whole bunch of instances in our CSS, used on every little thing from buttons to headline colours, such that if we ever modified our model colours away from Typekit inexperienced it could be a number of work to alter each occasion. Through the use of variables as an alternative of the uncooked hex code, it’s simple—simply change the variable (which you’ll outline on the high of your stylesheet, and even in a partial) and the brand new coloration seems in all places, immediately. You may even set variables to different variables, which helps preserve your fashion sheets semantic:

$typekit-green: "#99cc00";
$typekit-link-color: $typekit-green;a {
  coloration: $typekit-link-color;
}

You may assign nearly any sort of worth to a variable; aside from coloration hex values, they’re particularly good for font-family stacks:

$sans-serif-font: 'ff-dagny-web-pro', 'Helvetica Neue', Arial,  
Helvetica, 'Liberation Sans', sans-serif;
$serif-font: 'ff-tisa-web-pro', Georgia, Occasions, serif;.banner h1 {
  font-family: $sans-serif-font;
}

Mixins#section6

Mixins are reusable units of properties or guidelines that you simply embrace, or “combine,” into different guidelines. You outline them utilizing the @mixin key phrase, and embrace them utilizing the @embrace key phrase.

On this instance, I’m telling Sass to use all the fashion properties contained within the highlighted-bold-text mixin to all the span components inside .result-with-highlights

$highlight-color: #ffa;@mixin highlighted-bold-text {
  font-weight: daring;
  background-color: $highlight-color;
}.result-with-highlights {
  span {
    @embrace highlighted-bold-text;
  }
}

When you’ve outlined a mixin, you’ll be able to reuse it wherever else in the identical file. Right here I’m saying that components with a category named highlighted also needs to have the colour and font weight properties specified by the mixin:

.highlighted {
  @embrace highlighted-bold-text;
}

That is actually helpful for making use of new CSS3 properties to components, whereas guaranteeing huge cross-browser compatibility by way of vendor prefixes and fallback stacks. In common CSS, vendor fallbacks might be annoying to make use of as a result of they’re so verbose, which ends up in a number of boring copy-and-pasting. Sass mixins allow us to use new sorts of types in a bulletproof manner with out writing a number of code.

Right here I’ve outlined a mixin that applies 4px rounded corners to a component, utilizing vendor-prefixed properties for WebKit, Firefox, and IE, adopted by the usual border-radius property from the CSS3 spec. I’ve additionally outlined the nook radius as a variable so it’s simpler to alter in a while:

@mixin rounded-corners {
  $rounded-corner-radius: 4px;
  -webkit-border-radius: $rounded-corner-radius;
  -moz-border-radius: $rounded-corner-radius;
  -ms-border-radius: $rounded-corner-radius;
  border-radius: $rounded-corner-radius;
}.button {
  @embrace rounded-corners;
}

Mixins also can include entire nested guidelines, not simply properties. Here’s a model of the acquainted clearfix CSS hack applied as a Sass mixin:

@mixin clearfix {
 // For contemporary browsers
  &:earlier than,
  &:after {
    content material:"";
    show:desk;
  }  &:after {
    clear:each;
  }  // For IE 6/7 (set off hasLayout)
  & {
    zoom:1;
  }
}.group {
  @embrace clearfix;
}

The ampersand (&) selector is a Sass conference which means “this factor.” When this code is compiled Sass will exchange all of the & symbols with the present selector, on this case .group.

Making stylesheets smarter#section7

Utilizing mixins to use easy types is cool, however what makes mixins superior is that they will take arguments, identical to a perform in JavaScript or PHP. And you should utilize them together with extra superior options like expressions and capabilities to go far past group to implement some nice, complicated types.

Grid structure techniques are an excellent utility for Sass scripting. There are a number of ready-made 960px CSS grid techniques on the market, however most of them require you so as to add non-semantic class names to your code. To not point out the truth that to make use of considered one of these grids, it’s important to load all of the CSS for your complete system, even for those who solely plan to use a number of customary unit sizes.

For our ultimate instance, we’re going to implement a easy 12-unit grid in Sass. Moderately than outline class names for every grid unit, we’ll create a mixin that may apply the right width and margins to show any factor right into a unit of our grid.

First, we have to arrange our column and gutter widths as variables:

$column-width: 60px;    // 12 columns = 720px
$gutter-width: 20px;    // 11 gutters = 220px

Subsequent we’ll want Sass to do some math for us. A unit of our grid will span a sure variety of columns, plus all the gutters between these columns. To calculate the width, we’ll use the next components:

width = (column width — span) + (gutter width — (span – 1))

Now we are able to write our mixin. In contrast to the examples above, this mixin will take one argument—the span—which might be handed into our mixin as a variable. Every grid unit might be floated left, and to take care of the 20px gutter between columns, every unit may have a proper margin equal to the gutter width:

@mixin grid-unit($span) {
  float: left;
  margin-right: $gutter-width;
  width: ($column-width * $span) + ($gutter-width * ($span - 1));
}

Easy, proper? However there’s a number of energy in these few strains of code. We will implement a primary two-thirds structure with a most important content material space and a sidebar very merely, utilizing some extra semantically-named lessons and our Sass mixins:

.container {
  @embrace clearfix;
  @embrace grid-unit(12);
  float: none;
  margin: 0 auto;
}

.main-content {
  @embrace grid-unit(8);
}

.sidebar {
  @embrace grid-unit(4);
  margin-right: 0;
}

As helpful as that is—and I take advantage of some model of this grid calculator mixin on each venture I work on these days—this simply begins to scratch the floor of what’s doable with Sass. 

Sass’ help for primary math expressions assist make it a lot simpler to craft adaptive fluid-width layouts. Right here I’m utilizing Ethan Marcotte’s responsive-width components to create a extra responsive model of my primary grid above. Sass doesn’t convert between CSS items except particularly requested to, so I’ve wrapped my formulation in Sass’ built-in proportion() perform:

.container {
// end result = goal / context
  width: proportion(940px / 960px);  .main-content {
    // That is nested within .container, so its context is 940px
    width: proportion(620px / 940px);
  }  .sidebar {
    width: proportion(300px / 940px);
  }
}

There are additionally capabilities for reworking and adjusting colours—you can also make colours darker or lighter, or alter saturation or alpha transparency, proper inside your fashion sheet:

$base-link-color: #00f;
a {
  coloration: $base-link-color;
}
a:visited {
  // This reduces the lightness of the colour (in HSL phrases) 
  // by 50%, leaving hue and saturation alone
  coloration: darken($base-link-color, 20%);
}figcaption {
  // Generates an rgba() coloration worth with 50% opacity
  background-color: transparentize(#fff, 50%);
}

And if these capabilities aren’t sufficient you’ll be able to outline your personal, and share and reuse them throughout tasks as a easy partial. Take a look at the complete record of built-in SassScript capabilities for a style of what’s doable.

The official Sass web site is stuffed with helpful data, together with a whole reference information to the SCSS language. One factor chances are you’ll discover helpful immediately is that this record of obtainable SCSS textual content editor plugins, providing syntax highlighting and different helpful instruments for writing Sass code in your editor of selection.

As well as, Sass creator Hampton Catlin is at present ending up an in-depth guidebook to Sass for the Pragmatic Programmers, which you should buy and skim immediately by way of Pragmatic’s Beta Books program.

Past the core Sass language, there’s additionally Compass, a library of SCSS capabilities and patterns developed by Chris Eppstein, with built-in help for Eric Meyer’s CSS reset, the Blueprint grid system, plus tons of CSS3 and typographic results. Its authors have referred to as it “jQuery for stylesheets,” which is a fairly apt description. In the event you’re utilizing the Scout app, the Compass framework is already put in. In any other case, you could find directions for putting in and utilizing it on the Compass web site.

Leave a Comment