Using Bourbon, Neat, Bitters & Refills

So why am I contemplating using Thoughtbot products when Bootstrap is so popular and much widely used in the web community?

  • Bourbon – “A simple and lightweight mixin library for Sass.”
  • Neat – “A lightweight semantic grid framework for Sass and Bourbon.”
  • Bitters – “Scaffold styles, variables and structure for Bourbon projects.”
  • Refills – “…prepackaged patterns and components, built on top of Bourbon, Bitters, and Neat.”

The idea of using clean and semantic markup that is based entirely on Sass mixins was pretty much the key factor which attracted me to try out Bourbon, Neat, Bitters and Refills.

But don’t get me wrong, I’m not about to bash Bootstrap as I enjoy using it to flesh out projects that require quick turn-around times and I’ve also written a previous post on how to use semantic classes in Bootstrap.

As one of the co-creator’s of Neat, Reda Lemeden writes in his post Introducing Bourbon Neat, a Sass-based responsive grid framework, he states that:

We built Neat with the aim of promoting clean and semantic markup; it relies entirely on Sass mixins and does not pollute the HTML with presentation classes and extra wrapping divs. It is less explicit—as in requires fewer mixins—than most other Sass-based frameworks and comes with built-in table-cell layout support.

The main motivation behind Neat is allowing anyone to build fluid, entirely semantic grid layouts without having to wade through hundreds of lines of documentation. We also believe that giving designers the ability to override the default behavior without hassle is key.

For the simple fact that it’s lightweight in size and is based on Sass mixins was enough for me to experiment with this framework. It also means none of the bloated and unused code of the framework will weigh down the loading time of your site as only the mixins you’re using gets compiled (to get your final CSS output). This is definitely a huge plus.

However there are caveats of using Bourbon and Neat that should be kept in mind. In this post Create responsive grid layouts with Bourbon Neat, by Derek Blank, he states that “IE7+ support is possible when Bourbon is used with Selectivizr for CSS3 selectors and Respond.js for media queries.”

Experiences with Bourbon, Neat, Bitters and Refills

After watching the series on Awesome CSS with Bourbon, Neat, Bitters & Refills! by PHP Academy, I installed Bourbon, Neat and Bitters.

When I wanted to use refills (and after compiling), the following error message appeared:

"Error: $large-screen (refills) variable not defined"

In Part 6 of the series, I noticed that other people had similar issues to me when following this video tutorial.

So to overcome this error, I did the following:

  1. Doing a Google search I found this post

    But instead of uncommenting line #4 in bitters.scss, it’s now uncomment line #8 in the base.scss file.

  2. Then within the base folder, find grid-settings.scss and comment out:

    @import 'neat-helpers';
    

    and use:

    @import'../neat/neat-helpers';
    

    I’m making the assumption that you’re developing in a non-rails environment.

  3. And finally, the order of your @imports in your styles.scss need to be listed in this order:

    @import"bourbon/bourbon";
    @import"base/base";
    @import"neat/neat";
    

    Another assumption is that you’re using Neat.

Newbie Error

I wanted to include Normalize to my project but I made the mistake of naming: @import “normalize.css” in my main styles.scss file.

Instead I should re-name “normalize.css” to “_normalize.scss” as a partial file and therefore within my styles.scss file, the name of the normalize import should be:

@import "normalize"; 

The benefit of this is to reduce the number of http requests if you are linking directly to the normalize CSS file.

References:

Start using Sass

I really wanted to point out the reasons why web developers should start using Sass and I came across the Clean out your Sass junk drawer slides by Dale Sande. It shows just how much the thought process of well structured CSS has changed over the years. So if you still work with fellow front-end web developer/engineers who aren’t using any CSS Preprocessor, point them to these slides.

CSS3 Background-Image

While creating a prototype for a project (using Bootstrap), I added the Jumbotron component which is described as: “a lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site” and found that my background image wasn’t responsive at all.

After searching on Stack Overflow, I found that using “background-size: cover” to the Jumbotron class works to make the background image responsive. For example, see below:

.jumbotron{
    background: #efefef url(image.png) no-repeat center center fixed;
        -webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
}

So here’s a more in depth look at using “Responsive Full Background Image Using CSS” by Jacob Gube.

“The CSS background-size property can have the value of cover. The cover value tells the browser to automatically and proportionally scale the background image’s width and height so that they are always equal to, or greater than, the viewport’s width/height.” – Jacob Gube

Jacob continues to say that “to enhance the page load speed on small screens, we’ll use a media query to serve a scaled-down version of the background image file.” He further states the reason to use media queries is that “it’s a huge payload just for a background photo” which is never a good thing and that “it’s exceptionally bad on mobile internet connections”. Adding that “the image dimension is excessive on small-screen devices”.

Jacob wraps up his tutorial by stating, “if I can say just one cautionary thing about this technique, it’s this: Please use it with care because large files can severely affect UX, especially when our user is not on a fast or reliable Internet connection. This is also the reason why you should set a good default background color so the user can read the content while the background image is loading.”

So this is all well and good for the majority of browsers, except for IE8. If you look at Can I Use you will see that IE8 doesn’t support this CSS3 feature.

To overcome this issue, I found an article on “How to Enable Background Size in Internet Explorer” by Thoriq Firdaus.

Thoriq demonstrates how the CSS3 Background Size property can be used in Internet Explorer. He states that “unfortunately, this feature does not fallback nicely in Internet Explorer 8 and below. If you attach a very large image, it may overflow the container.”

So Thoriq mentions to use the Background Size Polyfill developed by Louis-Rémi. This polyfill “replicates the same behaviour of background-size property with cover and contain values. This polyfill comes in the form of an HTC file named backgroundsize.htc, and an .htaccess file, which is required when the page is served from Apache server to send the .htc mime-type.”

He goes on to provide the following instructions, “to use it, include the HTC file through the Internet Explorer behavior property, as follows.”

.background-size {  
        width: 500px;  
        height: 320px;  
        background-image: url('img/image.jpg');  
        background-size: cover;  
        -ms-behavior: url('http://example.com/js/backgroundsize.htc');  
    }

I’ve noticed in the code example above, that it’s probably not a good idea to give your class and CSS selector the same name eg. background-size.

He goes on further to instruct “…if you are using Apache server, place the .htaccess in the root folder of server or, simply add this line to the existing .htacces file, if available.”

AddType text/x-component .htc  

References:

Semantic classes in Bootstrap

According to Bootstrap, “you can modify the variables to your own custom values, or just use the mixins with their default values.”

Using @extend

An example of writing semantic code using Bootstrap is using @extend:

As written by Brad Borrow in the article Using Sass To Semantically @extend Bootstrap, he says that Bootstrap “makes it incredibly easy to write cluttered, non-semantic and non-reusable markup that will render correctly across all browsers.”

He goes on to explain what writing semantically means, “HTML documents are intended to be descriptive of their contents from an information hierarchy perspective. One should be able to read them and know what they are about, not how they will look.”

So to use Bootstrap semantically, Brad further states that we can “leverage the power of Sass’s @extend functionality to solve this problem. From Sass’s documentation: @extend works by inserting the extending selector anywhere in the stylesheet that the extended selector appears. This means we can use our semantic selectors and extend Bootstrap’s selectors to get all of its goodness.”

Using @mixins

Another example of writing semantic code using Bootstrap is by using mixins:

In this “Bootstrap and Sass” video (by Easy Dev Tuts) it shows us how to use Bootstrap’s mixins for Sass. You can also download the repository of this tutorial.

So instead of writing:

  <div class="container">
   ……
  </div>

From this example we include the mixin container-fixed to apply the container. In this example, it’s applied to the body tag:

body{
	@include container-fixed();
}

So instead of writing the following built-in Bootstrap classes in our HTML:

    <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-9"></div>
    </div>

We can create our own (of course, trying to be semantic as possible) such as the below, which will give the same results as using the above Bootstrap classes.

       .site-header{
		@include make-row(); // adds a row
		}
		.site-logo{
			@include make-sm-column(3); // adds a column
		}
		.site-nav{
			@include make-sm-column(9); // adds a column
		}
	}

Brett Jankford wrote an in-depth article about his thoughts on semantic HTML class names and maintainability.

While indicating the clear benefits of using Bootstrap and built-in classes, “frameworks like Twitter Bootstrap which use visual (presentational) class names are widely popular. Back-end developers that I’ve talked to that have used Twitter Bootstrap seem to really like it. They love the plugin-in-play ability with adding visual class names to elements. They don’t have to get in and mess around with the CSS, they can just add and remove classes as needed.”

There is a need to think about future maintainability of classes, “with individual role based classes, this flexibility is tricky. If we class the sections of the page individually, based on their role, with little thought to reusability, the CSS and the corresponding HTML classes offer little ease of maintenance and extensibility. If new sections are added, we need to add new role based classes along with additional CSS that corresponds to these new classes.”

To summarise

I’ve described various methods on how to use semantic classes using Bootstrap. It gets complicated when trying to come up with new semantic classes to replace Boostrap’s existing classes especially for components such as; the navbar, jumbotron and carousel to name a few.

So in the real world, can we really afford the time to completely re-structure classes to be semantic? It’s really up to your individual needs and the size of your project. You might only need to use semantic classes on the responsive grid structure but when it comes to using components, that will be challenging! And another thing to consider is, do you really need the extra bloat of a CSS framework or is it the responsive grid that you only need? (and there are a plethora of grid only frameworks).

To be semantic or not to be?

References

Further reading

Grunt build error behind proxy

While working on a project, I used the Yeoman webapp generator and selected; Bootstrap Sass, jQuery and Modernizr. Everything has worked well, the ‘grunt serve’ and ‘grunt test’ commands, however when I want to run the ‘grunt build’ command to upload the contents of my ‘dist’ folder to a web server, I get prompted with the following error:

Looking for Modernizr references in dist/styles/main.css >> svg
Downloading source files
A server error occurred attempting to download a file: 
Fatal error: connect ETIMEDOUT

I’m not sure if it’s something to do with my bower components or the proxy that I’m sitting behind?

At the moment, the workaround I’m using is to manually add the scripts (jQuery, Modernizr and Bootstrap) to the scripts folder then to link it to my html files. But surely there is a better way to do this?!

CSS3 Grayscale Filter

So I stumbled upon a quick video on YouTube on how to use the CSS3 grayscale filter upon hovering on an image.

The results can be seen below:

See the Pen hcBCJ by Adeline (@adelineyaw) on CodePen.

Click on the CSS tab in the Codepen example above to see how this filter effect can be implemented in your CSS.

Unfortunately this effect can’t be seen on Firefox as it’s not supported so please refer to “Can I Use” to find out if your browser supports this CSS3 filter.

“Method of applying filter effects (like blur, grayscale, brightness, contrast and hue) to elements, previously only possible by using SVG.” – Can I Use

“It’s worth noting that right now, CSS Filter Effects are an unoffical specification – however, the editors of the spec include representatives from Adobe, Apple and Opera, and we have already got implementations in Chrome, Safari and iOS 6.” – CSS3 Filters

References:

Preprocessing is for Everybody

Preprocessing is for Everybody by Chris Coyier

“You’ve heard about CSS preprocessors. If you have yet to take the dive or have only dipped your toes in, let Chris Coyier (CSS-Tricks, Codepen) convince you that you won’t regret it. Have you met resistance? Let’s try and convince your boss and colleagues. There may be some misconceptions going around that we need to nip in the bud. Then we’ll look at how preprocessors fit into the modern web development workflow, the evolving best practices for using them, and how to squeeze out all the benefit we can get from them.” – An Event Apart Video

Responsive Images

The following video is from the post Responsive Images using <picture> and srcset/sizes – by Matt Steele

Big heavy images are responsible for most of the bloat on a responsive website, but it doesn’t have to be that way. Here’s the latest HTML elements you can use to keep your images small, and your site lean & fast. – Matt Steele

Reference: Srcset and sizes

Features of Compass

“Compass is an open-source CSS Authoring Framework.” – Compass

“Compass can do some really handy tasks like measuring images from the filesystem and writing them into your stylesheets. Asset URL functions are available that make it easy to move assets around in a project or even switch to a content delivery network (CDN) without having to rewrite your stylesheets. Compass can even combine a directory of images into a single sprite image and do the otherwise tedious task of calculating coordinates and writing the spriting CSS for you.” – Sass and Compass in Action (Manning)


Some of the features of Compass I’ll be covering are:

CSS3

From my previous blog post, I used an example of a mixin for a box with a border-radius. This time instead of re-writing the prefixes seen below;

-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;

We can use the Compass mixin called border-radius.

For example:

Play with this gist on SassMeister.

And we can define the 10px in the parentheses when you include the mixin.

Image Sprites

Instead of having to use your preferred image editor to create your image sprite, Compass can do this for you. Simply throw in your icons into a specific folder and let the Compass Sprite utility, create the sprite and calculate the CSS positions for you. Another feature is that Compass also recognizes the hover state of your image by simply saving your image, eg. facebook_hover.png

The following excerpt is from the Spriting with Compass reference page

Basic Usage

**Note: The use of social is only for this example, “social” represents the folder name that contains your sprites.

The simplest way to use these icon sprites is to let compass give you a class for each sprite:

In your SCSS file, add the following:

@import "compass/utilities/sprites"; 
@import "social/*.png";
@include all-social-sprites;

And you’ll get the following CSS output:

.social-sprite, 
.social-facebook, 
.social-linkedin, 
.social-twitter, 
.social-youtube {
background-image: url('../img/social-sf14878b932.png'); 

// the name of your generated sprite image will be different

background-repeat: no-repeat;
}

.social-facebook {
background-position: 0 0;
}

.social-facebook:hover, .social-facebook.facebook-hover { 
background-position: 0 -80px;
}

.social-linkedin {
background-position: 0 -160px;
}

.social-linkedin:hover, .social-linkedin.linkedin-hover {
background-position: 0 -240px;
}

.social-twitter { 
background-position: 0 -320px;
}

.social-twitter:hover, .social-twitter.twitter-hover {
background-position: 0 -400px;
}

.social-youtube {
background-position: 0 -480px;
}

.social-youtube:hover, .social-youtube.youtube-hover {
background-position: 0 -560px;
}

This results in one single sprite image:

Compass Sprite example

You can now apply the social-your-class-name to your HTML as needed.

As stated earlier, the Sprite utility also recognizes if your icon requires a hover state. So add your hover state icons in the social folder (within your images folder).

Be sure to add in your “config.rb file” the location of your main images (root) folder.

Once you save the changes, the new sprite image will re-generate to include the hover state icons and thus your output CSS will also be updated. It is pretty amazing!

Font Face

The Compass Font Face provides a mixin to support @font-face. See CSS3 spec: @font-face.

This file can be imported using: @import “compass/css3/font-face”

Use the mixin font-face($name, $font-files, $eot, $weight, $style)

Where:

  • $name is required, arbitrary, and what you will use in font stacks.
  • $font-files is required using font-files(‘relative/location’, ‘format’). for best results use this order: woff, opentype/truetype, svg
  • $eot is required by IE, and is a relative location of the eot file.

See the Compass reference page for more details on this mixin and the use of $weight and $style.

For this example, I’m using the font called “TeXGyreHerosCnBold”.

In your SCSS file, add the following:

@include font-face("TeXGyreHerosCnBold", 
font-files(
"texgyreheroscn-bold-webfont.ttf", 
"texgyreheroscn-bold-webfont.eot", 
"texgyreheroscn-bold-webfont.svg", 
"texgyreheroscn-bold-webfont.woff")
);

Then assign your font, eg. h1, h2:

h1, h2 {
font-family: "TeXGyreHerosCnBold", Helvetica, sans-serif;
}

Add your fonts to the fonts folder and define the location of your fonts in the config.rb file, fonts_dir = “fonts”. This is the directory where the font files are kept. Standalone projects will default to “css_dir/fonts”. Rails projects will default to “public/fonts”.

Extending Compass

There are quite a number of Sass and Compass resources but I want to mention, Sache. As the site says “Find the perfect tool for your next Sass or Compass project. Discover Sass & Compass Extensions”. There are plenty of Sass and Compass extensions/plugins listed on the site and I’ll be writing a future blog post about using Susy (a semantic grid framework) as well as Breakpoint Sass (a plugin for media queries).


So hopefully I’ve convinced you to use or at least try out Compass with your next Sass project!

References

Learning Sass

What is Sass?

“Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.” – Sass

To install Sass, read the official Sass guide or if you’re trying to install Sass at your workplace and have issues due to your network firewall, read my previous blog post.

There are numerous ways to compile Sass. There’s the Command Line/Terminal or GUI’s such as Koala, Scout, Prepos and Codekit. Read the official Sass guide on the best way to compile your Sass to CSS.

I’ll briefly discuss some of the useful features of Sass:


Let’s begin to start using Sass!

Nesting

You can nest CSS rules inside each other instead of repeating selectors in separate declarations.

Play with this gist on SassMeister.

Nesting – Referencing Parent Selectors with &

Sass adds the ability to reference the current parent selector using the ampersand as a special placeholder.

An example of using the ampersand to reference the parent selector for a link and hover:

Play with this gist on SassMeister.

Variables

As described in the Sass Basics website.

“Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you’ll want to reuse. Sass uses the $ symbol to make something a variable. Here’s an example:”

When the Sass is processed, it takes the variables we define for $font-stack and $base and outputs normal CSS with our variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site.

We could even lighten the color, for example;

Play with this gist on SassMeister.

So the advantage is, if you need to update your brand colour, you just have to adjust the $base variable once in your SCSS file and not have to do a search and replace for all instances of that particular color.

Mixins

Where variables let you define and reuse values throughout the stylesheet, mixins allow you to define and reuse blocks of styles. Instead of typing the same rules multiple times in various declarations, use mixins to define a group of styles just once and refer to it anytime those styles are needed.

In addition, writing CSS3 can be tedious to write as there are many vendor prefixes that exist. So mixins lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes.

Here’s an example for border-radius.

Play with this gist on SassMeister.

To create a mixin you use the @mixin directive and give it a name. We’re also using the variable $radius inside the parentheses so we can pass in a radius of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.

Please note if you are using Compass with Sass, you can easily use Compass’ mixin ‘border-radius’ instead of creating your own. You just have to @import “compass” or @import “compass/css3/border-radius in your Sass file. Read the Compass reference for more information on how to use Compass. I’ll be discussing Compass in a future blog post.

@extend

We can use Sass’s @extend function to “chain together” styles that are shared amongst multiple selectors.

Use @extend when you want to store multiple static properties and pass them to selectors, it lets you share a set of CSS properties from one selector to another.

Play with this gist on SassMeister.

Placeholders

Placeholder are helpful in creating blocks of styles for design patterns that may or may not be used (eg. in frameworks or templates). Placeholders allow you to define “phantom” classes that won’t appear in your outputted CSS. You can reference placeholders using @extend.

For example, lets create a class for a block of styles that define a button.

We’ll use a placeholder selector, which prefixes the class name with a %.

Play with this gist on SassMeister.

We can call this rule set in other classes using @extend.

Partials

“You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is simply a Sass file named with a leading underscore. You might name it something like _partial.SCSS. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @import directive.” – Sass Basics

@import

“Sass extends the CSS @import rule to allow it to import SCSS and Sass files. All imported SCSS and Sass files will be merged together into a single CSS output file. In addition, any variables or mixins defined in imported files can be used in the main file.” – Sass Reference

“Sass builds on top of the current CSS @import but instead of requiring an HTTP request, Sass will take the file that you want to import and combine it with the file you’re importing into so you can serve a single CSS file to the web browser.” – Sass Basics

SCSS

// _reset.scss

html,
body,
ul,
ol {
   margin: 0;
  padding: 0;
}

/* base.scss */

@import "reset";

body {
  font-size: 100% Helvetica, sans-serif;
  background-color: #efefef;
}

When you import a file you don’t need to include the file extension .scss. Sass is smart and will figure it out for you. When you generate the CSS you’ll get:

CSS

html, body, ul, ol {
  margin: 0;
  padding: 0;
}

body {
  background-color: #efefef;
  font-size: 100% Helvetica, sans-serif;
}

@extend vs mixins

Where a mixin will write the same rules in each declaration it’s called from, @extend will create multiple, comma-separated selectors for shared styles. It’s good to keep this difference in mind when you’re deciding which to use.


Now to apply all of this in your projects!

Hopefully you’ve got a better understanding of how powerful Sass can be. I’ve only scratched the surface and have used extremely simple examples using the basics of Sass. There are advanced functions on top of what I’ve outlined in this blog post, for example; advanced maths and functions.


References