SASS, SCSS, CSS and Modular Design

What is SASS?

SASS, syntactically aware style sheet, is a CSS pre-processor and scripting language that allows you flexibility in creating your CSS rules. It provides several programmatic tools to make CSS creation easier.

The language is a superset of CSS3, allowing you to create the same CSS that you do by hand but with many additional features.

Install SASS

SASS is a Ruby-based command line utility gem. As such it requires Ruby and the Ruby Gems to be installed on your system. Mac and most Linux distributions come with both programs already installed. Windows users can use the Ruby Installer available from Ruby Forge.

Once Ruby and Ruby Gems are installed you can run the following command:

$ gem update --system
$ gem install sass

Run SASS from the command line

The best way to work with SASS is to run it from the command line (terminal on Linux and Macintosh, Command on Windows). Assuming SASS was installed as explained above with a command like the following:

$ sass \
--update \
--scss \
--style expanded 
--line-numbers --line-comments \
file.scss

This command does the following:

  • –update tells sass that we’re interested in updating the resulting CSS file.

  • –scss indicates that we are using the SCSS syntax on the source file(s)

  • –style expanded tells SASS to use the expanded style for the resulting CSS. SASS has 4 styles: nested ( the default), compact, compressed, or expanded.

I normally use the expanded style as it makes the CSS result easier to read by me and by anyone else who may be working on the project with me.

  • –line-numbers and –line-comments will inset comments regarding the source file and the line number in the original source file for each of your CSS declarations. This makes troubleshooting your SCSS files easier.

  • file.scss is our driver file for the project.

There is another option, particularly useful during development. You can have SASS watch either a file or a directory for changes and automatically

$ sass \
--scss \
--style expanded 
--line-numbers --line-comments \
--watch input-dir:output-dir

The only difference is the –watch input-dir:output-dir which tell SASS both the input directory and the output directory separated by a colon (:) and to update the corresponding CSS files every time a file changes in the input directory.`

Are SASS and SCSS the same?

SASS is the original syntax for the language, developed along similar lines to the HAML project. The SASS syntax eliminates a lot of the complexities of CSS; You don’t need to use {} to begin or end a block, you don’t need ; to finish statements in CSS blocks.

SCSS (Sassy CSS) is a separate dialect or syntax for SASS and it’s the one we will cover in this document. It is fully compatible with CSS (all valid CSS documents are valid SCSS documents) and it provides an easier entry point to SASS for people who are already familiar with CSS.

What makes SASS special?

If you’ve done any amount of work with CSS you will find that you repeat code and patterns over and over in your stylesheets. I’ve also wished that there ways to reduce the number of statements you have to write to accomplish a given task.

SASS provides a set of shortcuts, patterns and functions that assist designers and developers when building CSS content

Variables

Rather than having to type the same name or value over and over again, SASS allows you to create variables that you can use throughout your stylesheets. For example we can define our colors as variables and then use the variables wherever we would use the color definition.

$red: #cc092f;

/* Link Formatting */

a {
  color: $red;
}

The main advantage of variables is that we need to only change one value and then recompile the stylesheet for the changes to be reflected everywhere the variable appeared in the document.

Nesting

How many times you’ve found yourself creating CSS like this and then have to remember which elements were you applying the style to.

h2 {
  font-size: 36pt;
}

h2 .warning {
  color: #f00;
}

h2 .important {
  font-weight: bold;
}

With SASS you can nest the code for your H2 declarations into something that will result in the code above with less typing and a lot more legibility. The SASS code looks like this:

h2 {
  font-size: 36pt;
    .warning {
    color: #f00;
    }
    .important {
  font-weight: bold;
    }
}

In the example above it’s easy to see the result but when you start nesting deeper than two levels you can see how useful this feature is.

Mixins, parameters and default parameters

One of the most powerful features of SASS are mixins; the ability to insert code in multiple places throughout your stylesheets. For example, you can define a mixin for the border properties of an element:

@mixin solid-thin {
  border-width: thin;
  border-style: solid;
}

And call it from anywhere in your document using something like:

.video video {
  margin: 20px auto;
  border-color: $red;
  @include solid-thin;
}

img {
    margin: 0 auto;
    border-color: $red;
    @include solid-thin;
}

Once again, if we need to make changes we make them where the @mixin declaration is made and it will be reflected everywhere we include the mixin using the @include tag.

You can also use parameters to further modularize the content of your mixin, including the use of default parameter.

$radius: 5px !default;

@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
     -moz-border-radius: $radius;
      -ms-border-radius: $radius;
       -o-border-radius: $radius;
          border-radius: $radius;
}

and then call it with a value to replace the $radius variable or the default of 5px if the a value for the $radius variable is not set.

.box {
    @include border-radius(10px);
}

You can use mixins to further modularize your code and to make it easier to maintain. The mixins and variables don’t need to be included in the same file. We will discuss modularization later in this document.

Another use of mixins is for testing. Rather than write the same piece of code over and over throughout your stylesheets. For example let’s say that you’re not sure if you want your border to be thin or thick (two predefined values in the CSS standard)

Inheritance

We’ve all found ourselves repeating the same CSS fragments over and over again. Look at the example below (and yes, I know it’s poor CSS coding, but it will do as an example)

.meessage {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: green;
}

.error {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: red;
}

.warning {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
  border-color: yellow;
}

By using SASS extension mechanism we can isolate the repeating code in one place and then only code the differences. The code looks like the one below:

.meessage {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  @extend .message;
  border-color: green;
}

.error {
  @extend .message;
  border-color: red;
}

.warning {
  @extend .message;
  border-color: yellow;
}

Mathematical Operations

There are times when we want to do something that requires some sort of calculation to produce a result. Sass has a basic set of math operators like +, -, *, /, and %. The example below (taken from the SASS documentation guide) calculates percentages for our article and aside tags.

.container { width: 100%; }

article[role="main"] {
  float: left;
  width: 600px / 960px * 100%;
}

aside[role="complimentary"] {
  float: right;
  width: 300px / 960px * 100%;
}

One thing to note. Whatever we do with calculations needs to be converted to the unit we are working with (percentages in this case) otherwise they will be treated as a string

Functions

SASS provides a variety of Functions that make working with CSS easier.

The functions I use the most are Opacify and Transparentize which change the opacity (transparence level) of a given color without us having to setup special variables or functions to do so.

opacify(rgba(0, 0, 0, 0.5), 0.1) 
            => rgba(0, 0, 0, 0.6)
opacify(rgba(0, 0, 17, 0.8), 0.2) 
            => #001

transparentize(rgba(0, 0, 0, 0.5), 0.1) 
            => rgba(0, 0, 0, 0.4)
transparentize(rgba(0, 0, 0, 0.8), 0.2) 
            0=> rgba(0, 0, 0, 0.6)

Enhanced @media and @media queries support

@media directives in SASS behave just like they do in plain CSS, with one extra capability: they can be nested in CSS rules. If a @media directive appears within a CSS rule, it will be pushed up to the top level of the stylesheet, and use all the selectors inside the rule. For example:

.sidebar {
  width: 300px;
  @media screen and (orientation: landscape) {
    width: 500px;
  }
}

is compiled to:

.sidebar {
  width: 300px; }
  @media screen and (orientation: landscape) {
    .sidebar {
      width: 500px; }
}

You can also nest media queries on your SASS stylesheets and the selectors will be combined using the and operator on the top level of the resulting CSS file. This SCSS declaration:

@media screen {
  .sidebar {
    @media (orientation: landscape) {
      width: 500px;
    }
  }
}

is compiled to:

@media screen and (orientation: landscape) {
  .sidebar {
    width: 500px; }
}

Finally, @media queries can contain Sass Script expressions (variables, functions, and operators) in place of values in the declarations.

Partials and imports

Partials allow for code modularity. You can create small snippets of SCSS and then call them from another SCSS file.

In order to create the snippets, what SASS calls a fragment, create a normal file but begin the name with an underscore (_). This will instruct the SASS compiler (discussed in detail later in this article) to not include the file in the compilation.

Once you have created all the snippets and are happy with the way they look you can create the main file. The instructions for this process will be discussed in the next section, when we talk about the SASS repository project.

The SASS repository

As I’ve worked in SASS I’ve developed a series of snippets and partial files to make my life easier and to share them with the #eprdctn community and other interested parties. The snippets live in their own github repository which you can clone and send pull requests to.

The idea is that, as we develop new concepts or ideas we can build our partials and share them to get feedback and suggestions for improvements.

How do the snippets work

Partials (also known as snippets) are full SCSS files that are not processed directly when converting the files to CSS but are included on a master file that I refer to as driver using the @import command as shown in the example below, under build index file.

Note that the SCSS files are only referenced by name, not by the full name + extension.

When running the driver file through SASS, it will take each of the partials and add their content to the file that imported them.

Creating your own

In order to create a partial file just write it out as you would any other SCSS stylesheet but name it with an underscore (_) as the first character of the file name; _toc.scss or _images.scss.

Build index file

Once you have your fragments you can add them to your main file (what I call index or driver) using the @import command. The example below will add the content of each partial file in the order they appear in the driver file.

/*
Example of a driver SCSS file. Only this file will get processed when we run the SASS command line tool. It will call all the partials as they are found.
*/

@import "_reset";
@import "_multimedia";
@import "_headings";
@import "_lists";
@import "_columns";
@import "_marginalia";
@import "_toc";
@import "_images";
@import "_footnotes";

Compile Stylesheets

Once you have created your fragments and drivers it is time to compile the SASS files into your final CSS; just like we did when compiling a single SCSS file.

$ sass \
--update \
--scss \
--style expanded 
--line-numbers --line-comments \
file.scss

File.scss in this case is our driver. The fragments will be incorporated in to the driver file in source order.

What we didn’t cover

There is more to SASS than what we’ve covered so far. These areas are not essentials for beginners, or I haven’t figured out how they are essential.

The Compass framework

The compass framework uses SASS to provide tools and utilities to make it easier to work with CSS in your web sites or applications. As part of the utilities it provides a large set of functions to augment those provided by the default SASS installation.

It is installed separately from SASS using rubygems

gem update --system
gem install compass

It may need to be installed as an administrator on OS X and Unix systems.

As interesting as it seems, I have yet to find a compelling enough reason to move to Compass from ‘plain’ SCSS.

One of the biggest drawbacks of compass, in my opinion, is that it requires you to start everything from scratch with its own directory structure; not optimal if you’re moving an existing project to the framework. The SASS documentation states that as of SASS 3.1.0 Compass users can now use the –compass flag to make the Compass libraries available for import. This will also load the Compass project configuration if run from the project root. I have yet to test it.

Some typographical mixins may convince me it’s worth to switch.

Programming-like functions

In addition to the functions discussed above, SASS 3.1.0 introduces functions directly into SCSS files. In the example below (Taken from the SASS documentation page) you can see an example of what these functions look like:

$grid-width: 40px;
$gutter-width: 10px;

@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { 
    width: grid-width(5); 
}

SASS functions allow us to be even more flexible in our stylesheets by introducing our own logic to the resulting CSS code.

The experiment continues

I’ll post more as I continue to play and experiment with SASS and related tools.

Stay tuned 🙂

How Does Digital Affect Funding

Gone are the days where you had hoped that a big investor would see your project and hope that you’d make enough money to recoup the investors’ money and maybe, if you’re lucky, make some yourself.

Music, books and games have benefited greatly for crowdfunding. Unlike traditional funding sources is the number of backers and the amounts that people have raised. They also provide with payment system where the money is held in escrow and, in the case of Kickstarter, only paid out if the process is successful in raising all its funds.

Crowdfunding (alternately crowd financing, equity crowdfunding, crowd-sourced fundraising) is the collective effort of individuals who network and pool their money, usually via the Internet, to support efforts initiated by other people or organizations.[1][2] Crowdfunding is used in support of a wide variety of activities, including disaster relief, citizen journalism, support of artists by fans, political campaigns, startup company funding,[3] motion picture promotion,[4] free software development, inventions development, scientific research,[5] and civic projects.[6]

From Wikipedia

Kickstarter and Indiegogo are two examples of crowd funding platforms. They provide tools and infrastructure for individuals or groups to raise money for their projects. These platforms also allow you to communicate with your supporters and build community around your project by creating two-way communication between the project and its backers.

Kickstarter will only release the funds if the project reaches its minimum level of funding. Indiegogo gives you the options of full funding or partial funding on project completion date. Both of them have deeply changed the way we fund our projects.

I prefer the Kickstarter’s fundraising model as it helps sets expectations for a project’s backer. If you don’t rise the full funding and the site released the funds, where are the remaining funds coming from? People tend to expect that the fully funded project will happen even if the project only achieves partial funding.

It is not unheard of games and other content to get over 1 million dollars on funding. Meeting and beating stretch goals; what they call the funding goals raised in excess of their initial funding, and usually with extra rewards attached, and additional products related to the fundraising that can be purchased at a discounted price.

One of my favorite examples of successful crowd funded projects is Ukiyo-e heroes

The project is very niche specific. It seeks to create traditional Japanese wood prints using modern video game characters as a way to pay homage to the characters’ roots in Japanese tradition.

The project raised over 310,000 dollars, many times over their modest goal of $10,400. The project not only raised a huge amount of money but it also built a community of people who are interested in the product and who can be tapped for additional funds through additional Kickstarter projects or through direct sales. The potential is endless.

The additional funding Ukiyo-e Heroes raised has allowed David Bull, the Japanese printmaker who created the prints for the project, to keep his art alive by hiring apprentices and experienced printmakers to work in the project. The impact was felt way beyond the virtual community of backers in Kickstarter.

Look at the most successful Kickstarter publishing projects in terms of funding. Look at the broad definition of publishing and the variety of projects that get funded under this category.

I’ve chosen 3 different projects to highlight some of these new publishing methods and results.

  • Ukiyo-e heroes
  • Art Space Tokyo
  • Mind’s Eye Theater: Vampire the Masquerade

 

Who is a publisher and How do you define publishing?

What happens when a publisher has a tight, direct connection with readers, is able to produce intellectual property that spreads, and can do both quickly and at low cost?

Seth Godin About the Domino project

From western4ul @ Flickr

Digital tools have expanded the definition of publishing to something I would have never thought possible 10 or even 5 years ago. For every author that makes a big publishing deal (like those mentioned in this Mashable 2009 article) there are hundreds if not thousands of niche authors selling their books directly to interested audiences either through their websites, through an aggregator or through the big vendors like Apple’s iBookstore and Amazon’s Kindle Direct Publishing program.

We are able, if we choose to, to connect directly with our audiences and interact in ways that were not possible before the advent of web technologies. We can turn our blogs and wikis as our communication channel with the audience, using their feedback and engagement as a measure of what content we should work with, edit and refine over time; maybe even using audience engagement as the metrics for additional content and conversion to other formats.

Some examples of this new publishing medium include, among others:

PressBooks

PressBooks uses WordPress as the engine behind a multi publishing paradigm. It gives authors a familiar interface, many people are used to WordPress as either a blogging or content management platform so how we write our content doesn’t change much from how we write traditional blog posts.

The interface produces web content (hosted in the Pressbook platform), epub and PDF content. Pressbook has also entered in partnerships with book distributors to provide a turnkey solution for people interested in self publishing.

The Atavist

Atavist is a media and software company at the forefront of digital, mobile publishing. Our mission is to enable the next generation of multimedia storytelling, reaching readers across mobile devices and the Web.

Our flagship publishing arm, The Atavist—built on Creatavist—features original pieces of longform, nonfiction journalism. Sold individually on mobile devices and e-readers as “e-singles,” The Atavist is digital-first, pushing the boundaries of multimedia publishing while always emphasizing the story above all.

https://www.atavist.com/our-story/

The Atavist is as close as I’ve found to what I envision a future publishing enterprise. It is clean, multi format and it’s never a cookie cutter exercise; not all stories are available in all formats but when they use a format they take full advantage of available capabilities.

Formats supported by the Atavist application for given article

Hi

Hi takes the opposite approach to The Atavist. Hi uses short 30 word moments with required location and an optional photograph. Other community members can request that you expand the moment with additional text; you can accept or decline the request.

I particularly like the way that Hi builds community by allowing users to request additional information about moments and subscribing to people who you’re interested in: every time they write an expanded moment. I like this concept as much, if not better, than Twitter.

Docbook, XML and ebooks:Creating eBooks the old fashioned way

One of the most traditional ways to author content for multiple distribution channels is to roll up your sleeves, write XML and then convert it to your target format. For this exercise we will use Docbook. Without going into too much detail, Docbook was initially created in 1991 as a means to create computer software manuals and other technical documentation. Over the years Docbook has evolved into a general purpose XML authoring language. Along with the authoring standard, what structures we can use to author our content, the authors of the Docbook standard have also created a set of stylesheets to convert our base XML files into different formats. One of the formats that you can convert your XML files is epub.

More information about the history of Docbook can be found in the Docbook: The Definitive Guide website

Getting Started

Below is a skeleton XML file for a Docbook-based book.

<?xml version="1.0" encoding="utf-8"?> 
<book xmlns='http://docbook.org/ns/docbook' version="5.0" xml:lang="en"> 
<title>The Adventures of Sherlock Holmes</title>
<info>
 <author>
   <personname>
     <firstname>Arthur</firstname>
     <surname>Conan Doyle</surname>
   </personname>
 </author>
</info> 
<chapter>
 <title>A Chapter</title></chapter></book></p>

<p><para>Content is required in chapters too.</para>

Once we have the XML document ready (filling out the skeleton with as many chapters as we need to complete our content), we need two things:

  • A set of XSLT stylesheets to convert our XML into HTML and ePub
  • A processor to actually run the transformation The stylesheets are located at

http://sourceforge.net/projects/docbook/files/docbook-xsl-ns/1.76.1/ where you can choose if you want .zip or .tag.gz compressed archives. In addition download the file at http://sourceforge.net/projects/docbook/files/epub3/docbook-epub3-addon-b3.zip and http://sourceforge.net/projects/docbook/files/epub3/README.epub3. To enable ePub3 support follow the instructions on the README.epub3 file.

The stock Docbook style sheets produce ePub 2 compliant books. This is ok for now as most readers that support ePub support this version. There is experimental support for ePub 3 compliant books, which we will follow for this article as it gives us access to all the multimedia features of ePub3.

As far as XSLT processors there are two that I recommend. One is Saxon; currently at version 9.4 and available from its publisher Saxonica on a trial basis. Yes, it is commercial software but after years of using it I highly recommend the investment. It is written in Java and provides a full set of features, extensions and advanced implementations of XML related technologies. For our purposes it’s enough that it will take the XML, process it with the style sheets and give us the output we want.

The second processor I recommend is XSLTProc. written in C and bundled with Most UNIX/Linux/OSX installations it can be downloaded/updated from the xmlsoft.org web site. Download and install both LibXML and LibXSLT and install them in the same order (LibXML first and then LibXSLT) or it will not work as you think it will.

The commands to create the ebooks using Xsltproc are:

xsltproc /Users/carlos/docbook/1.0/xslt/epub3/chunk.xsl ebook.xml

This produces an output that should look like this:

Writing OEBPS/bk01-toc.xhtml for book 
Writing OEBPS/ch01.xhtml for chapter 
Writing OEBPS/ch02.xhtml for chapter 
Writing OEBPS/index.xhtml for book 
Writing OEBPS/docbook-epub.css for book 
Generating EPUB package files. 
Generating image list ... 
Writing OEBPS/package.opf for book 
Writing OEBPS/../META-INF/container.xml for book 
Writing OEBPS/../mimetype for book 
Generating NCX file ... 
Writing OEBPS/toc.ncx for book 
< ?xml version="1.0" encoding="UTF-8"?> ' 

Final Details

We are done generating the content and the files we need in order to generate the eBook. To finish the process we need to do the following (taken from the README.epub3 file):

Manually copy any image files used in the document into the corresponding locations in the $base.dir directory.

For example, if your document contains:

<imagedata fileref="images/caution.png"></imagedata>

If the base.dir attribute is set up to the ebook1/OEBPS, you would copy the file to: ebook1/OEBPS/images/caution.png. You can get a list of image files from the manifest file (ebook1/OEBPS/package.opf in our example) that is created by the style sheet.

Currently the stylesheets will *not* include generated image files for callouts, header/footers, and admonitions. These files have to be added manually.

cd to the directory containing your mimetype files, which would be ebook1 in this example.

Run the following zip commands to create the epub file

zip -X0 sherlock-holmes.epub mimetype 
zip -r -X9 sherlock-holmes.epub META-INF OEBPS [/bash] 

The first command adds the ‘mimetype’ file first and uncompressed. The -X option excludes extra file attributes (required by epub3). The numbers indicate the degree of compression. The -r option means recursively include all directories. The “sherlock-holmes.epub” in this example is the output file.

Validation

Because we have done most of the work manually we need to validate the result of our work. For that we will use the epubcheck3 tool available from its Google Code Project repository.

java -jar /Users/carlos/Java/epubcheck-src-3.0b3/dist/epubcheck-3.0b3.jar sherlock-holmes.epub

Hopefully we’ll see a result like this

Epubcheck Version 3.0b3 No errors or warnings detected.