CommonLounge Archive

HTML & CSS Preprocessors

July 02, 2018

A preprocessor is a tool that transforms one type of code into another type. In this tutorial, we will look into two popular preprocessors: one for HTML (called Haml) and the other one for CSS (called Sass). Haml and Sass are much more easier to write, and provide a few very useful features out-of-the-box which are not available in HTML or CSS. Thus, by writing in Haml or Sass, and then using a preprocessor to convert your code into HTML or CSS respectively, you can simplify your development process quite a lot.

Haml

Haml stands for HTML abstract markup language. It aims to provide a good structure and makes your HTML code DRY (Don’t Repeat Yourself), logical, and easier to read. We will see an example below to see how it does this.

Installation

Ruby is required to be installed for Haml. If you’re using a Mac or Linux, Ruby should be pre-installed on your computer. Otherwise, you can install Ruby by following the directions here.

Next, you’ll need to install the haml preprocessor itself. It’s available as a Ruby Gem, and this is how you can install it:

gem install haml

Now that you have the haml preprocessor, you can convert haml files to html files with this command:

haml home.haml home.html

Here the file home.haml is converted to home.html.

You can use haml --help to check various options available with this command.

Doctype and HTML Elements

Now that we know how to convert .haml to html, let’s look what a typical haml file looks like.

First, the DOCument TYPE is identified with 3 exclamation marks. So,

! ! ! 5

is compiled to:

<!DOCTYPE html>

Elements are declared using the % sign. Either tabs or spaces can be used for indentation. But the two should not be mixed. For example,

%body
  %header
    %h1 Advanced CSS
    %h2 Let us look at preprocessors.
  %section
    %p Lorem ipsum dolor sit amet.

It is compiled to the following html code:

<body>
  <header>
    <h1>Advanced CSS</h1>
    <h2>Let us look at preprocessors</h2>
  </header>
  <section>
    <p>Lorem ipsum dolor sit amet.</p>
  </section>
</body>

Attributes

Attributes can be declared using { } or ( ).

%img{:src => "commonlounge.jpg", :alt => "CommonLounge"}
%img{src: "commonlounge.com", alt: "CommonLounge"}
%img(src="commonlounge.jpg" alt="CommonLounge")

All three lines above compile to the same line of code:

<img src="commonlounge.jpg" alt="CommonLounge">

Classes and IDs

Classes can be set with values using .

IDs can be set with values using the #

%section.feature
%section.feature.special
%section#hello
%section#hello.feature(role="region")

compiles to

<section class="feature"></section>
<section class="feature special"></section>
<section id="hello"></section>
<section class="feature" id="hello" role="region"></section>

Div classes and id’s don’t need the div keyword before . or #

.awesome
.awesome.lesson
#getting-started.lesson

compiles to:

<div class="awesome"></div>
<div class="awesome lesson"></div>
<div class="lesson" id="getting-started"></div>

Comments

Individual comment lines are marked by a forward slash /. Code can be commented by being nested under a forward slash.

  %div
    / Commented line
    Actual line
  /
  %div
      Commented block

compiled to:

  <div>
    <!-- Commented line -->
    Not Commented
  </div>
  <!--
    <div>
      Commented block
    </div>
  -->

Conditional comments are marked by writing the condition in square brackets after a forward slash /

/[if lt IE 9]
  %script{:src  => "html5shiv.js"}

compiles to

<!--[if lt IE 9]>
  <script src="html5shiv.js"></script>
<![endif]-->

Comments that need not be displayed are called silent comments. They are marked by a dash -#

%div
  -# Removed line
  Actual line

compiles to:

<div>
  Actual line
</div>

Filters

Haml provides a number of filters as a shorthand for writing different types different types of code/input. Filters can be used by typing a colon and the name of the filter. Custom filters can also be defined. Here are some of the popular ones:

:css, :javascript, :sass, :ruby, :textile, :scss, :sass, :markdown

Here’s a JavaScript example:

:javascript
  alert('Javascript here!');

compiles to:

<script type='text/javascript'>
  //<![CDATA[
    alert('Javascript here');
  //]]>
</script>

Sass and SCSS

Sass stands for Syntactically Awesome Stylesheets. It is a preprocessing language that can be compiled to CSS. SCSS is Sassy CSS — it’s a more flexible preprocessing language as it allows you to write plain CSS as well.

Installation

As with Haml, Ruby is a prerequisite for Sass and SCSS. Once Ruby is installed, execute the following command to install the sass preprocessor:

gem install sass 

Convert .scss or .sass files to .css files with the following command:

sass <filename>.sass <filename>.css

You can also convert entire directories to css files by checking the files for updates and converting with the command:

sass --watch myfolder/sass:public/css

Sass syntax is easier but it has a learning curve. SCSS, on the other hand, is fully compatible with CSS and easy to read. Let us look at some examples of how a CSS file is compiled from Sass code.

Nesting Selectors

Selectors can be nested inside other selectors. Nesting properties such as padding, margin, border and font can be used. Here is an example:

  div
   font:
     family: Arial, serif
      style: normal
      weight: bold

complies to:

  div {
    font-family: Arial, serif;
    font-style: normal;
    font-weight: bold;
  }

To combine selectors, you can use &

a
  color: #0087cc
  &:hover
    color: #ff7b29

compiles to:

a {
  color: #0087cc;
}
 a:hover {
  color: #ff7b29;
}

Comments

The standard CSS syntax /*..*/ works in Sass files. Silent comments are flagged with two forward slashes //

These comments are not visible in the CSS files complied.

/* Normal comment */
div
  background: #333
// Omitted comment
strong
  display: block

compiles to:

/* Normal comment */
div {
  background: #333;
}
strong {
  display: block;
}

Variables

Variables can be defined by a $ sign, and then reused later. This is one of the most powerful features of Sass.

$font-base: 1em
$serif: "Helvetica Neue", Arial, "Lucida Grande", sans-serif
p
  font: $font-base $serif

compiles to:

p {
  font: 1em "Helvetica Neue", Arial, "Lucida Grande", sans-serif;
}

Calculations

Sass has features for mathematical calculations such as addition, subtraction, multiplication, division and other number functions.

width: 40px + 6
width: 40px - 6
width: 40px * 6
width: 40px % 6

compiles to:

width: 46px;
width: 34px;
width: 240px;
width: 4px;

Color operations, color manipulation, color alterations and HSLa color alterations can be done.

For example:

width: percentage(1) will be compiled as width: 100%

width: round(3.5px) will be compiled as width: 4px

Extends

Extends can be used to share and reuse styles. Extends can be set using the @extend rule with the selector to be extended. It helps in reuse of code thus making your code more DRY.

.alert
  border-radius: 10px
  padding: 10px 20px
.alert-error
  @extend .alert
  background: #f2dede
  color: #b94a48

compiles to:

.alert,
.alert-error {
  border-radius: 10px;
  padding: 10px 20px;
}
.alert-error {
  background: #f2dede;
  color: #b94a48;
}

Mixins

Mixins are template properties and values that you can share among different selectors. @mixin is used to configure mixins. In this example, we are creating an object called design with certain dimensions -

  @mixin design() {
    bottom: 0;
    left: 2;
    position: absolute;
    right: 0;
    top: 2;
  }

This can be used as follows:

  .modal-background{
    @include design();
    background: blue;
  }

compiles to:

  .modal-background{
    bottom: 0;
    left: 2;
    position: absolute;
    right: 0;
    top: 02
    background: blue;
  }

In Sass, multiple files can be imported and condensed into one file. It helps in better organization and more efficient HTTP requests.

Sass also supports control directives like the For loop, If loop, conditionals, operators and While loops.

There are other preprocessors such as Slim, LESS, Stylus etc. Sass and SCSS are well integrated with Ruby and have good community support.

Summary

In this tutorial, you learned two important preprocessors:

  • Haml, stands for HTML abstract markup language
  • Sass, stands for Syntactically Awesome Stylesheets

Haml and Sass are much more easier to write, and provide a few very useful features out-of-the-box which are not available in HTML or CSS.


© 2016-2022. All rights reserved.