Sunday, 30 March 2014

Preprocessors

In time writing HTML and CSS may feel a bit taxing, requiring a lot of the same tasks to be completed over and over again. Tasks such as closing tags in HTML or repetitively having to looking up hexadecimal color values in CSS.
These different tasks, while commonly small, do add up to quite a bit of inefficiency. Fortunately these, and a handful of other inefficiencies, have been recognized and preprocessor solutions have risen to the challenge.
A preprocessor is a program that takes one type of data and converts it to another type of data. In the case of HTML and CSS, some of the more popular preprocessor languages include Haml and Sass. Haml is processed into HTML and Sass is processed into CSS.
Upon setting out to solve some of the more common problems, Haml and Sass found many additional ways to empower HTML and CSS, not only by removing the inefficiencies but also in creating ways to make building websites easier and more logical. The popularity of preprocessors have also brought along different frameworks to support them, one of the more popular being Compass.

Haml

Haml, known as HTML abstraction markup language, is a markup language with the single goal of providing the ability to write beautiful markup. Serving as its own markup language, code written in Haml is later processed to HTML. Haml promotes DRY and well structured markup, providing a pleasing experience for anyone having to write or read it.

Installation

Haml requires Ruby to be compiled to HTML, so the first step to using it is to ensure that Ruby is installed. Fortunately for those on Mac OS X Ruby comes preinstalled, and those on a Windows machine may visit Windows Installer for directions. Upon confirming Ruby is installed the gem install haml command needs to be run from the command line, using Terminal or the alike command line program, to install Haml.
  1. gem install haml
Files written in the Haml markup should be saved with the file extension of .haml. To then convert these files from Haml to HTML the haml command below needs to be run to compile each individual file.
  1. haml index.haml index.html
In the example above, the file index.haml is converted to HTML and saved as index.html within the same directory. This command has to be run within the same directory the files reside in. Should the command be run outside this directory the path where the files reside need to be included within the command. At any time the command haml --help may be run to see a list of different available options.

Watching a File or Directory

Unfortunately Haml doesn’t provide a way to watch a file, or directory, for changes without the use of another dependency.
Inside of a Rails application a Haml dependency may be added in the Gemfile, thus automatically compiling Haml files to HTML upon any changes. There are a few desktop applications available for those not using Rails, one of the more popular being CodeKit.
On top of Haml CodeKit also supports other preprocessors, which may also come in handy.

Doctype

The first part to writing a document in Haml is knowing what type of doctype is to be used. When working with HTML documents, the general document type is going to be the HTML5 doctype. In Haml document types are identified with three exclamation points, !!! followed by any specifics if necessary.
The default doctype in Haml is the HTML 1.0 Transitional document type so in order to make this the HTML5 doctypethe number five has to be passed in after the exclamation points, !!! 5.
HAML
  1. !!! 5
COMPILED HTML
  1. <!DOCTYPE html>

Declaring Elements

One of the defining features of Haml is its syntax, and how to declare and nest elements. HTML elements generally have opening and closing tags, however within Haml elements only have one tag, the opening. Elements are initialized with a percent sign, %, and then indented to identify nesting. Indentation with Haml can be accomplish with one or more spaces, however what is important is that the indentation remain consistent. Hard tabs or spaces cannot be mixes together, and the same number of tabs or spaces must be the same throughout an entire document.
Removing the need for both opening and closing tags, as well as mandating the structure with indentation creates an easy to follow outline. At any given time the markup can be scanned and changed without struggle.
HAML
  1. %body
  2. %header
  3. %h1 Hello World
  4. %section
  5. %p Lorem ipsum dolor sit amet.
COMPILED HTML
  1. <body>
  2. <header>
  3. <h1>Hello World</h1>
  4. </header>
  5. <section>
  6. <p>Lorem ipsum dolor sit amet.</p>
  7. </section>
  8. </body>

Handling Text

Text within Haml can be placed on the same line as the declared element, or indented below the element. Text cannot be both on the same line as the declared element and nested below it, it has to be either or. The example from above could be rewritten as the following:
  1. %body
  2. %header
  3. %h1
  4. Hello World
  5. %section
  6. %p
  7. Lorem ipsum dolor sit amet.

Attributes

Attributes, as with elements, are declared a bit differently in Haml. Attributes are declared directly after the element in either {} or (), all depending if you wish to use Ruby or HTML syntax. Ruby style attributes will use the standard hash syntax inside of {}, while HTML style attributes will use standard HTML syntax inside of ().
HAML
  1. %img{:src => "shay.jpg", :alt => "Shay Howe"}
  2. %img{src: "shay.jpg", alt: "Shay Howe"}
  3. %img(src="shay.jpg" alt="Shay Howe")
COMPILED HTML
  1. <img src="shay.jpg" alt="Shay Howe">

Classes & IDs

If you wish to, Class and ID attributes may be declared the same as all other attributes, however they may also be treated a bit differently. Rather than listing out the class or ID attribute name and value inside {} or () the value can be identified directly after the element. Using either a . for classes or a # for an ID the value can be added directly after the element.
Additionally, attributes may be mixed and matched, chaining them together in the appropriate format. Classes are to be separated with a . and other attributes may be added using one of the previously outlined formats.
HAML
  1. HAML CLASSES & IDS%section.feature
  2. %section.feature.special
  3. %section#hello
  4. %section#hello.feature(role="region")
COMPILED HTML
  1. HAML CLASSES & IDS<section class="feature"></section>
  2. <section class="feature special"></section>
  3. <section id="hello"></section>
  4. <section class="feature" id="hello" role="region"></section>

Division Classes & IDs

In the event a class or ID is used on a div the %div may be omitted, and the class or ID value can be used outright. Again, classes are to be identified with a . and IDs are to be identified with a #.
HAML
  1. HAML CLASSES & IDS.awesome
  2. .awesome.lesson
  3. #getting-started.lesson
COMPILED HTML
  1. HAML CLASSES & IDS<div class="awesome"></div>
  2. <div class="awesome lesson"></div>
  3. <div class="lesson" id="getting-started"></div>

Boolean Attributes

Boolean attributes are handled just as they would be within Ruby or HTML, all depending on the syntax being used.
HAML
  1. %input{:type => "checkbox", :checked => true}
  2. %input(type="checkbox" checked=true)
  3. %input(type="checkbox" checked)
COMPILED HTML
  1. <input type="checkbox" checked>

Escaping Text

One of the benefits of Haml is the ability to evaluate and run Ruby, however this isn’t always the desired action. Text, and lines of code, can be escaped by using a backslash, \, allowing the text to be rendered explicitly without being executed.
In the example below, the first instance of = @author is executed Ruby, pulling the authors name from the application. The second instance, starting with the backslash, is escaped text, printing it as is, without execution.
HAML
  1. .author
  2. = @author
  3. \= @author
COMPILED HTML
  1. <div class="author">
  2. Shay Howe
  3. = @author
  4. </div>

Text Escaping Alternatives

Occasionally escaping text doesn’t quite do the job and Ruby is needed to generate the desired output. One popular instance of this is when trying to include a period directly after a link, but not as part of the anchor text. Putting the period on a new line isn’t acceptable as it will be treated as an empty class value, causing a compiling error. Adding a backslash before the period will escape the character however it places a blank space between the last word and the period. Again, not producing the desired output.
In these cases a Ruby helper comes in handy. In the example below, the helper is used to place a period directly after the last word but still outside of the anchor text.
HAML
  1. %p
  2. Shay is
  3. = succeed "." do
  4. %a{:href => "#"} awesome
COMPILED HTML
  1. <p>Shay is <a href="#">awesome</a>.</p>

Comments

As with elements and attributes, comments are handled a bit differently in Haml as well. Simply enough, code can be commented out with the use of a single forward slash, /. Individual lines may be commented out with the use of a forward slash at the beginning of the line, and blocks of code can be commented out by being nested underneath a forward slash.
HAML
  1. %div
  2. / Commented line
  3. Actual line
  4. /
  5. %div
  6. Commented block
COMPILED HTML
  1. <div>
  2. <!-- Commented line -->
  3. Actual line
  4. </div>
  5. <!--
  6. <div>
  7. Commented block
  8. </div>
  9. -->

Conditional Comments

Conditional comments are also handled differently in Haml. To create a conditional comment use square brackets, [], around the condition. These square brackets need to be placed directly after the forward slash.
HAML
  1. /[if lt IE 9]
  2. %script{:src => "html5shiv.js"}
COMPILED HTML
  1. <!--[if lt IE 9]>
  2. <script src="html5shiv.js"></script>
  3. <![endif]-->

Silent Comments

Haml also provides the ability to create Haml specific comments, or silent comments. Silent comments differ from general HTML comments in that upon being complied any content within a silent comment is completely removed from the page, and is not displayed in the output. Silent comments are initialized with a dash then the number sign, -#. As with other comments, silent comments may be used to remove one line or multiple lines with the use of nesting.
HAML
  1. %div
  2. -# Removed line
  3. Actual line
COMPILED HTML
  1. <div>
  2. Actual line
  3. </div>

Filters

Haml provides a handful of filters, allowing different types of input to be used inside of Haml. Filters are identified with a colon followed by the name of the filter, :markdown for example, with all of the content to be filtered nested underneath.

Common Filters

Below are some of the more common filters, with the more popular ones of the group being :css and :javascript.
  • :cdata
  • :coffee
  • :css
  • :erb
  • :escaped
  • :javascript
  • :less
  • :markdown
  • :maruku
  • :plain
  • :preserve
  • :ruby
  • :sass
  • :scss
  • :textile

Javascript Filter

HAML
  1. :javascript
  2. $('button').on('click', function(event) {
  3. $('p').hide('slow');
  4. });
COMPILED HTML
  1. <script>
  2. $('button').on('click', function(event) {
  3. $('p').hide('slow');
  4. });
  5. </script>

CSS & Sass Filters

HAML
  1. CSS & SASS FILTERS:css
  2. .container {
  3. margin: 0 auto;
  4. width: 960px;
  5. }
  6. :sass
  7. .container
  8. margin: 0 auto
  9. width: 960px
COMPILED HTML
  1. CSS & SASS FILTERS<style>
  2. .container {
  3. margin: 0 auto;
  4. width: 960px;
  5. }
  6. </style>

Ruby Interpolation

As previously mentioned Haml can evaluate Ruby, and there may occasionally be times where Ruby needs to be evaluated inside of plain text. In this event Ruby needs to be interpolated, accomplished by wrapping the necessary Ruby code inside #{}.
Below is an example of Ruby being interpolated as part of a class name.
HAML
  1. %div{:class => "student-#{@student.name}"}
COMPILED HTML
  1. <div class="student-shay">

Saturday, 15 March 2014

SCSS & Sass

SCSS & Sass

SCSS and Sass are preprocessing languages which are compiled to CSS, resembling Haml a bit in that they make writing code easier, and provide quite a bit of leverage in doing so. Individually SCSS and Sass come from the same origin however they are technical different syntaxes.
Sass, Syntactically Awesome Stylesheets, came first and is a strict indented syntax. SCSS, Sassy CSS, followed shortly after providing the same firing power of Sass but with a more flexible syntax, including the ability to write plain CSS.

Installation

As with Haml, SCSS and Sass are compiled using Ruby therefore Ruby needs to be installed to produce CSS files. Please follow the directions from before to install, or ensure Ruby is installed.
Once Ruby is installed the gem install sass command needs to be run from the command line to install SCSS and Sass.
  1. gem install sass
Files written in SCSS or Sass need to have the .scss or .sass file extensions respectively. To convert either of these file types to .css the following sass command needs to be run.
  1. sass styles.sass styles.css
The command above takes the styles.sass Sass file and compiles it to the styles.css file. As with Haml, these file names are paths and need to be executed respectively. The above command works when those files reside within the directory from which the command is run, should the files reside outside of the directory their path needs to be explicitly stated within the command.
Should changes to a file be ongoing Sass can watch the file and recompile the CSS every time a change takes place. To watch a Sass file the following sass command may be run.
  1. sass --watch styles.sass:styles.css
Additionally, instead of compiling or watching individual files, Sass is capable of compiling and watching entire directories of files. For example, to watch an entire directory of Sass files and convert them to CSS the sass command below may be run.
  1. sass --watch assets/sass:public/css

Converting Files from SCSS to Sass & Vice Versa

On top of being able to convert SCSS and Sass files to CSS you can also convert files from SCSS to Sass and vice versa. To do so the Sass commands below may be used to convert a SCSS file to Sass, and then a Sass file to SCSS respectively.
  1. # Convert Sass to SCSS
  2. sass-convert styles.sass styles.scss
  3. # Convert SCSS to Sass
  4. sass-convert styles.scss styles.sass

Syntax

As previously mentioned the primary difference between SCSS and Sass is their syntax, and their difference in severity. The syntax of SCSS isn’t much different than that of regular CSS. In fact, standard CSS will run inside of SCSS. Sass on the other hand is fairly strict, and any indenting or character errors will prohibit the styles from compiling. Sass omits all curly brackets, {}, and semicolons, ;, relying on indentation and clear line breaks for formatting.
SCSS
  1. .new {
  2. color: #f60;
  3. font-weight: bold;
  4. span {
  5. text-transform: uppercase;
  6. }
  7. }
SASS
  1. .new
  2. color: #f60
  3. font-weight: bold
  4. span
  5. text-transform: lowercase
COMPILED CSS
  1. COMIPLED SCSS & SASS.new {
  2. color: #f60;
  3. font-weight: bold;
  4. }
  5. .new span {
  6. text-transform: uppercase;
  7. }

Saturday, 1 March 2014

Responsive Flexible Embed Container

Flexible Embedded Media

Unfortunately the max-width property doesn’t work well for all instances of media, specifically around iframes and embedded media. When it comes to third party websites, such as YouTube, who use iframes for embedded media this is a huge disappointment. Fortunately, there is a work around.
To get embedded media to be fully responsive, the embedded element needs to be absolutely positioned within a parent element. The parent element needs to have a width of 100% so that it may scale based on the width of the viewport. The parent element also needs to have a height of 0 to trigger the hasLayout mechanism within Internet Explorer.
Padding is then given to the bottom of the parent element, the value of which is set in the same aspect ratio of the video. This allows the height of the parent element to be proportionate to that of it’s width. Remember the responsive design formula from before? If a video has an aspect ratio of 16:9, 9 divided by 16 equals .5625, thus requiring a bottom padding of 56.25%. Padding on the bottom and not the top is specifically used to prevent Internet Explorer 5.5 from breaking, and treating the parent element as an absolutely positioned element.
HTML
  1. <figure>
  2. <iframe src="https://www.youtube.com/embed/4Fqg43ozz7A"></iframe>
  3. </figure>
CSS
  1. figure {
  2. height: 0;
  3. padding-bottom: 56.25%; /* 16:9 */
  4. position: relative;
  5. width: 100%;
  6. }
  7. iframe {
  8. height: 100%;
  9. left: 0;
  10. position: absolute;
  11. top: 0;
  12. width: 100%;
  13. }

Flexible Embedded Media Demo

100% WIDE CONTAINER
75% WIDE CONTAINER
50% WIDE CONTAINER