Mastering Sass - Luke Watts - E-Book

Mastering Sass E-Book

Luke Watts

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Create interactive and responsive cross-browser apps with SASS and Compass

About This Book

  • Create data-intensive, highly scalable apps using Sass and COMPASS
  • Master the concepts of Sass and COMPASS and unleash your potential to develop enterprise-grade apps
  • This book is an experts' guide on leveraging Sass and COMPASS features

Who This Book Is For

This book is aimed at those who know CSS3 and HTML5 quite well and who've built a few small-to-medium-sized websites from scratch using Sass and Compass.

What You Will Learn

  • Master Sass and Compass features
  • Familiarize yourself with CSS and HTML concepts that are vital for a good Sass workflow.
  • Build real-world websites focusing on layouts and content aspects
  • Work on a grid system using Compass and Susy
  • Automate your workflow with Gulp
  • Write functions and mixins to leverage the control flow

In Detail

CSS and Sass add elegance and excellence to the basic language, and consist of a CSS-compatible syntax that allows you to use variables, nested rules, mixins, inline imports, and much more.

This book will start with an overview of the features in Sass and Compass, most of which you'll already be familiar; however, this will ensure you know what's expected as the book goes deeper into Sass and Compass. Next you will learn CSS and HTML concepts that are vital to a good Sass workflow. After all, Sass exists to simplify writing CSS, but it won't teach you how to make clean, scalable, reusable CSS. For that, you need to understand some basic concepts of OOCSS, SMACCS, and Atomic Design.

Once you've brushed up on the important concepts, it's time to write some Sass. Mainly you'll write a few functions and mixins that really leverage control flow using @if / @else loops and you'll learn how to figure out when and why things are going wrong before they bring you to a stop. Moving further, you'll learn how to use @debug, @warn and @error to properly handle errors.

You'll also learn about Gulp and how to use it to automate your workflow and reduce your repetitive tasks. And finally you'll learn about sourcemaps. With sourcemaps, you'll be able to write, debug, and view your Sass and Compass all from within the browser. It'll even LiveReload too!

As a bonus, you'll take a look at that funky Flexbox, currently all the rage! You'll learn how powerful and flexible it really is, and how you can use it with Compass. Best of all, it falls back very gracefully indeed! In fact, you'll be able to apply it to any existing project without having to change a line of the original CSS.

Style and approach

This book will provide readers with practical, actionable expertise to enhance their knowledge

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 366

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering Sass
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Requirements
Ruby, Sass, and Compass
Ruby
Ruby installer for Windows
Updating Ruby for Windows
Updating Ruby for Mac
Sass and Compass
Node and NPM
HTML5
HTML
CSS
Programming
The command line
Windows and Unix users
Windows
Unix (Mac and Linux)
You know your command line
Summary
2. Sass – The Road to Better CSS
A bit of sassy reminiscing
Setting up our project
Sass
C'mon, where's the Sass already?!
Command line options in Sass
Watching files and directories
Compile files and folders
Force Sass to compile
CSS output style
Sourcemaps
On the right heading!
A better If
Our heading sizes mixin
Three things you should know about lists
Heading line heights
But wait, there's more...
Allowing for different font families for each heading
Remove repetition
Error handling and type validation
Data types in Sass
@error
@debug
@warn
Bonus round
Summary
3. Compass – Navigating with Compass
Setting up a Compass project
Typography with Compass
What is vertical rhythm?
Vertical rhythm for images
A few things you need to know
Breakpoints and media queries
Aspect ratio
Sizing our headings
CodePen or SassMeister
Getting setup
CSS3, Compass, and Vendor prefixes
CSS regions
Columns
Transforms
Animations
Lists
Floating is a hack
Tag clouds
Sticky footer, stretching, and sprites
Compass and the future
Summary
4. CSS and HTML – SMACSS, OOCSS and Semantics
The good and the bad of CSS grids
Semantics
Naming conventions
OOCSS - Object-Oriented CSS
Separation of structure from skin
Separating container from content
Atomic Design
SMACSS
Base
Layout
Modules
State
Theme
Why aren't you using HSL?
A look at hue, saturation, and lightness
Don't use Photoshop to get HSL values
reset.css versus normalize.css
reset.css
normalize.css
sanitize.css
Make your own
Summary
5. Advanced Sass
Variables
!default
Variable scope
Local scope
!global flag
Variable scope in functions
Deeply nested variable scope
Making arrows in Sass
Come back, !important, all is forgiven
@content directive
Using @content for media queries
Maps
Summary
6. Gulp – Automating Tasks for a Faster Workflow
Setting up our project
Creating our folder and files
Why Gulp and not Grunt?
Node and npm
Node.js, node-sass, and fileWatch
Watching for changes and writing to a file
Setting up Gulp
Gulp watch
BrowserSync
Summary
7. Sourcemaps – Editing and Saving in the Browser
What are source maps and why should you care?
Setting up Source Maps in Firefox
Minor Gulp, Source Maps and BrowserSync issue
Setting up Source Maps in Chrome
Summary
8. Building a Content-Rich Website Components
Setting up our project
Gulp
Adding jQuery
Helpers
Function – get
Mixin – hover links
Mixin – bp (breakpoint)
Mixin – media (based on the OOCSS media component)
normalize.scss
Global base styles
Screen reader text
Layout – grid
Ionicons
Top nav
Grid – container
Search component
Main nav
Cart slide-out component
Mixin – media centered
Footer
Summary
9. Building a Content-Rich Website – Layout
Installing Susy
Setting up a basic grid
The container mixin
The span mixin
The last keyword
The $susy configuration map
Setting up a grid system
The concept of our grid system
The breakpoints
The columns naming convention
Building the grid
Testing the grid
The header
Main header inner
Main nav
Mobile menus
Top nav
Main nav
Image banner
Featured products
Testimonial
Subfooter and footer
The markup
The SCSS
Finishing touches
Summary
10. Building a Content-Rich Website – Theme
Typography
Dropcaps
Tagcloud
Color scheme
Search
Image banner
Featured products
Testimonials
Services
Footer
Section titles
Summary

Mastering Sass

Mastering Sass

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: August 2016

Production reference: 1230816

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-336-1

www.packtpub.com

Credits

Author

Luke Watts

Copy Editor

Safis Editing 

Reviewer

Bartosz Skupień

Project Coordinator

Ulhas Kambali 

Commissioning Editor

Amarabha Banerjee

Proofreader

Safis Editing 

Acquisition Editor

Prachi Bisht 

Indexer

Rekha Nair

Content Development Editor

Onkar Wani 

Graphics

Kirk D’Penha

Technical Editor

Shivani K. Mistry

Production Coordinator

Melwyn Dsa

About the Author

Luke Watts is a web developer and digital artist from Galway, Ireland. He started learning web design in 2012 after many years working with AutoCAD in the manufacturing industry. In 2014 he set up his own web development agency called Affinity4 (http://affinity4.ie) in Galway, Ireland. He is an Oracle Certified MySQL Developer, and an Adobe Certified Associate (Photoshop and Dreamweaver).

Luke has a keen interest in learning and teaching others. He has written articles for many websites, including his own blog, on a wide range of subjects such as SEO, WordPress Development, SVG, Sass, Jade, OOP, Git, Silex, MySQL, and PHP.

Luke is also an accomplished artist, both in traditional mediums (mostly pencil and ink) and in digital painting. When not building websites or writing code he will most likely be working on a digital painting on his Wacom tablet using Photoshop or creating a 3D model or scene in any number of 3D modeling applications.

I'd like to thank Gareth Milligan, who, from the very beginning showed me what web design had to offer, not only as a career, but also as a hobby. His advice, encouragement, and support in those early days of learning web design and when setting up my own company, helped me greatly. I'd also like to thank Marc Patterson, who helped me get through the difficult MySQL exams and who started me on my journey into PHP and programming.

To my friends, and colleagues who helped me stay positive and focused while writing this book. I would not have made it this far without each of your support. Also, thank you to my family who have always encouraged me and given me the courage to take on such a challenge. To my mother and father, this book is mostly dedicated to you. I miss you both terribly.

I'd also like to acknowledge the web design community. It has always been welcoming and open to newcomers. Designers and developers are always eager to share their knowledge and hard work with the community others. It’s that open spirit which keeps this industry going and makes it the most exciting and rewarding industry to work in.

Finally, I would like to thank Packt, who gave me this amazing opportunity. Thank you so much! I've enjoyed working with you all immensely and hope it won't be the last time.

About the Reviewer

Bartosz Skupień is highly motivated interactive developer with a good technical knowledge and open mind for all frontend technical news. Pixel perfection and a good eye for any kind of design are his strong abilities. He is eager to learn new skills and competencies, and is not afraid to make mistakes but able to draw conclusions. He is a team person, always willing to contribute own experience and best practices to make improvements. Creative Engineer who likes working in big global projects putting in force the latest styling trends and solutions. Currently working for a global company helping enterprises deploy digital solutions that transform their business.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.

Preface

The Web is moving fast! Since its boom in popularity in the late 90's to the early 2000's, web technology has begun to move at breakneck speed. However, while programming languages such as JavaScript, PHP, Ruby, Python, Java and others were developed to be quite well suited for their purposes on the Web, one of the core languages was holding everyone back…CSS. For almost a decade, developers and web designers had to devise numerous clever hacks and workarounds to make up for the shortcomings of this simple language. That's right! CSS is meant to be simple! A very conscious decision was made to omit variables, functions, loops, and conditional statements from CSS. This was to make it simple for beginners. When the W3C even started to consider introducing variables into the CSS specification it was met with opposition by many who felt it would make it too difficult for non-programmers and beginners.

The revolutionary movement that sparked the debate (and subsequent introduction) of CSS variables was started by one of Hampton Catlin's projects called Sass. In 2006, Hampton created Haml. The goal of Haml was to simplify writing HTML by removing the need for closing tags, instead using nesting and a Ruby-like syntax. Around the same time, he released Sass, which was a very similar idea, but for CSS. While Haml has not been as successful perhaps, Sass has quickly become a favorite, if not an industry standard among designers and developers. Yet the original indented Sass syntax was still a turn-off for many designers. It was perhaps too far removed from the familiar curly braces and semi-colons of CSS for many to embrace.

However, when the SCSS syntax arrived, Sass exploded into life. You couldn't read a web design blog, watch a tutorial, or go to a conference without Sass being at least mentioned. This surge in popularity was largely because with the newer SCSS syntax you could write plain old CSS if you wanted and work in the other features at your own pace. It was relatively easy for beginners to get on board with it, once they got passed working with the command line.

So why all the excitement about Sass in the first place. Well, Sass as you probably know by now, gives you access to variables, functions, loops, conditionals and many other features which allow for code reuse. Things which CSS lacks. These are things which, once you've started using them to write CSS you'll begin to wonder how anyone writes CSS without it.

Regardless of what stage you're at with Sass, this book aims to show you what it is truly capable of, using working examples and real-world situations. We'll work through setting up projects, we'll look at Compass, sourcemaps, using Sass with NodeJS, Gulp, and Susy. We'll also talk about writing good CSS and some useful best practices and methodologies to know, such as SMACSS, OOCSS, and BEM, which will help you organize and manage large projects. Then after all that, we'll put it all together to create a mobile-first homepage for an e-commerce website.

What this book covers

Chapter 1, Requirements, covers the software and libraries which will be used throughout this book. Here, we'll discuss more than what you'll need installed, we'll also look at some required knowledge too, such as the commonly used command line/terminal commands and some HTML and CSS examples.

Chapter 2, Sass – The Road to Better CSS, will cover setting up a Sass project and taking control of the CSS output. We'll also be writing mixins and functions to create some baseline typography styles. We'll then look at using the !default flag, lists, nesting, loops, and error handling and debugging to create more robust, usable code.

Chapter 3, Compass – Navigating with Compass, will look at creating a project using Compass. We'll look at how to take control of the default options through the command line, including what directories Compass creates by default, and where. We'll look at the many functions and mixins Compass has.

Chapter 4, CSS and HTML – SMACSS, OOCSS and Semantics, will talk about some CSS and HTML concepts which are vital to a good Sass workflow, such as OOCSS, SMACSS, BEM, and Atomic Design, and also why you should convert to using HSL instead of RGB or HEX color codes.

Chapter 5, Advanced Sass, will look at some of the more advanced features of Sass. We'll dive into the nuances of variable scope, using extends and mixins for better code resuse, the @content directive and maps.

Chapter 6, Gulp – Automating Tasks for a Faster Workflow, will start working on our final project. We'll look at installing and configuring Gulp, and installing various plugins and setting up tasks to automatically watch our project for changes and compile Sass and sourcemaps, and then reload the browser. All in one keystroke!

Chapter 7, Sourcemaps – Editing and Saving in the Browser, what source maps are and why you should care. We'll look at setting up sourcemaps to work in Firefox and Chrome with a few short examples of how this can be really useful when designing in the browser.

Chapter 8, Building a Content-Rich Website Components, will continue with our final project. We'll use many of the functions and mixins we wrote before to create reusable, configurable components as the core of our design. 

Chapter 9, Building a Content-Rich Website – Layout, will install and set up Susy through bower. Once that is done we'll create a complete mobile-first grid system using breakpoints and the built in Susy mixins. 

Chapter 10, Building a Content-Rich Website – Theme, we'll conclude our design, by giving it some color and style. We'll work out what fonts to use to best match the brand indentity of the project, and we'll add some eye catching elements such as dropcaps, tag clouds and stylish title underlines.

What you need for this book

To follow along with the examples in this book you will need Ruby version 2.1.7 or greater. You will then need the latest Compass and Sass gems. The Compass gem will install Sass also. You will also need NodeJS and npm. Npm will come built in with NodeJS. Any version after 4.2.1 will do. Finally, you will need Bower which can be installed through npm.

Not to worry…in Chapter 1, Requirements,  we will cover installing Ruby, Compass, Sass, and NodeJS.

Who this book is for

This book is aimed at those who know CSS3 and HTML5 quite well and who've built a few small-to-medium-sized websites from scratch using Sass and Compass.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other Sass files through the use of the @import directive."

A block of code is set as follows:

@import '../../bower_components/susy/sass/susy'; $susy: (     columns: 12, ) $breakpoints: (     sm: 480px,     md: 768px,     lg: 980px ); @each $size, $value in $breakpoints {     @media (min-width: map-get($breakpoints, $size) {         @for $i from 1 through map-get($susy, columns) {             .col-#{$i}-#{$size} {                 @include span($i);                 &-last {                     @include span($i last);                 }             }         }     } }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[@import '../../bower_components/susy/sass/susy'; $susy: (     columns: 12, ) $breakpoints: (     sm: 480px,     md: 768px,     lg: 980px ); @each $size, $value in $breakpoints {     @media (min-width: map-get($breakpoints, $size) {         @for $i from 1 through map-get($susy, columns) {             .col-#{$i}-#{$size} {                 @include span($i);                 &-last {                     @include span($i last);                 }             }         }     } }

Any command-line input or output is written as follows:

$ sass -–update assets/sass/main.sass:assets/css/main.css -–style=expanded

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Sass. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1.  Requirements

One of the hardest things to overcome when learning any specific web development topic is what I like to call the void. The void is that place where most of us get when we've covered all the essentials and beginner stuff. We've watched all the beginner videos and read the essential books and we're confident we're past being a beginner, but we're not quite an advanced user. We're in the void that sits in between those two states.

You know you're in the void because all the beginners stuff is too easy, but all the advanced material seems to start a step too far ahead, almost like they start on step 3 and you're missing steps 1 and 2. I think we fall into the void because somewhere after being a beginner we all continue on very different paths, no matter what we're learning. We pick up different tools and tricks to make our daily task quicker and easier.

This chapter's goal is to try and avoid the void by quickly going over what I personally use and will be using throughout this book. I'm not just talking about the stuff you'll need installed, I'm also talking about some required knowledge too.

We will cover the following topics:

Installing Ruby, Sass, and CompassUpdating Ruby, Sass, and CompassInstalling or updating Node and NPMRequired HTML, CSS, and programming knowledgeBasic command line/terminal knowledge

Ruby, Sass, and Compass

If you've used Sass and Compass before, then you already have installed them. However, I'd like to ensure your versions of Ruby, Sass, and Compass are all what they need to be to follow along with the examples I'll use later in the book. Many of the topics will use the very latest features of Sass and Compass.

Ruby

Sass and Compass run on a language called Ruby. Ruby became very popular in web development by offering clean syntax while still being very powerful. It achieves this power and simplicity by being strictly object oriented. In simple terms, everything from a single letter to a full class is treated as its own object in Ruby, meaning you can treat everything in Ruby much the same way. There are no second class citizens in Ruby.

In this book, we won't be working directly with Ruby; however, you do need it installed for Sass and Compass. So let's look at getting set up.

Ruby installer for Windows

I'm currently working on Windows. Yes, you read that correctly, I'm one of those weirdos who is actually more productive using Windows than Mac. So, for those of you on Windows, you'll know we don't have Ruby on our systems by default. It's not a big issue. You just go to http://rubyinstaller.org/downloads/ and you'll find a list of all available .exe installers for the stable Ruby versions.

Tip

What version should I use?

I like to always be one step behind on this one. What I mean by that is, at the time of writing, the current stable release of Ruby is 2.2.3. The previous stable release was 2.1.7. So I have 2.1.7 installed. The reason I choose to do this is gems are more likely to have been updated to work with at least 2.1.7.

Updating Ruby for Windows

I also have Ruby 1.9.3p551 installed on my system, and updating wasn't as straightforward a process as installing was. So, let's quickly explain how to install multiple versions of Ruby and switch between them if you need to.

The following method will allow you to have multiple Ruby versions installed but will require editing your PATH manually to switch between versions:

To start with, simply download and run the installer as normal. The RubyInstaller executable creates a separate folder for each Ruby version so you don't have to uninstall or overwrite your current version.Select your language and read and accept the License Agreement.Next, you'll be asked what directory to install Ruby into and also whether to Install Td/Tk Support, Add Ruby executables to your PATH, and Associate .rb and .rbw files with this Ruby installation. You can keep the defaults here, as shown in the following screenshot:

Installing Ruby on Windows

Next, you may need to update your system Path manually to use the newer version of Ruby. To check this, simply open the cmd.exe (WinKey + R, then type cmd and hit Enter). Then, type the following command:ruby -v

If your version is incorrect, you'll need to update your PATH variable manually. I'll also explain why this happens, seeing as it's actually a common problem with some applications.

Note

After you've switched to a new version of Ruby, you'll need to install your gems again for that version. To see what gems you have installed you can run gem list.

To update your PATH you'll need to open up your System Properties. You can do this by going to your Windows start screen and typing System Environment Variables and selecting the first option, Edit your system's Environment Variables.Next, select Environment Variables.
System properties
Then you'll need to set your System variables | Path value. The installation process will update the PATH variable for the user account but not the global path variable.
Setting the System Variables path
Replace the incorrect version of Ruby with the newer version you wish to use.

Note

The correct format is C:\Ruby21-x64\bin;, with no trailing slashes, and do not include the .exe executables.

To check everything is working, open cmd again and type ruby -v. You should see the correct version.

Updating Ruby for Mac

There are many more options for installing/updating Ruby for Mac. Depending on your OS version, you'll already have either 1.8.x or 2.0.x installed on your system by default. However, if you haven't updated, you may want to update to 2.1.7 or later. To do this, you can use Homebrew to easily update to the latest release with the following command:

brew install ruby

If you wish to have multiple version of Ruby on your system, you may want to look into a package manager such as Ruby Package Manager (RVM). You can learn more about RVM from their website at http://rvm.io/.

Sass and Compass

This one is easy. I'm using the most up-to-date versions of Sass and Compass, Sass 3.4.19 (Selective Steve) and Compass 1.0.3 (Polaris). If this is your first time installing Sass and Compass or you recently upgraded your version of Ruby, then the easiest way to install both is to simply install Compass using the following command:

gem install compass

Again, you can check everything is working by running the following command:

sass -v && compass -v

This will run each command one after the other.

Node and NPM

Node is somewhat more straightforward to install and update. I'm running 4.2.1; however, 5.0.0 is the most up-to-date release.

Note

You will need NodeJS to follow along with Chapter 6, Gulp – Automating Tasks for a Faster Workflow, and Chapter 7, Sourcemaps – Editing and Saving in the Browser.

You can install/update NodeJS by simply downloading and installing Node from https://nodejs.org/en/download/.

Also, running the installers with Node already installed will simply update Node, so there is actually no need to uninstall Node first.

To check your version of Node, you can open the command line and type (I'm sure you can guess it by now...) the following command:

node -v

HTML5

Like most languages or tools in the web development industry, Sass requires knowing a few other things first. When I say HTML5 I do of course mean CSS3 as well. JavaScript is also often grouped in with the HTML5 family; however, for what we'll be covering, you'll only need to be proficient with HTML5 and CSS3.

HTML

The following markup and elements should all be familiar:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Mastering Sass: Example</title> </head> <body> <header> <h1>Mastering Sass</h1> </header> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <main> <section> <article> <header><h2>Post No 2</h2></header> <div><p>Some more text</p></div> <footer><time>2015-11-12 13:00</time></footer> </article> <article> <header><h2>Post No 1</h2></header> <div><p>Some text</p></div> <footer><time>2015-11-12 12:00</time></footer> </article> </section> <aside> <h3>Sidebar</h3> <p>Sidebar Text</p> </aside> </main> <footer> <p>&copy; 2015 Mastering Sass</p> </footer> </body> </html>

CSS

With regard to CSS3, I'll be covering most of what we'll need to know, but a good idea of the properties that still require browser prefixes is always extremely useful, especially when using Compass.

We won't be doing much (if anything) with animations or transforms, but we might use some transition effects.

You should understand how to use pseudo-elements and selectors comfortably. Pseudo-elements are ::before and ::after, while the selectors include :first-child, :last-child, and ::nth-child(n). I always put the double colon (::) before the pseudo-elements. They will work with a single colon (IE8 will work with a single colon), but technically they should have two. The idea is that pseudo-elements typically are to do with content, while pseudo-selectors are referencing a specific HTML element or elements, such as first or last paragraphs, or the third list item in an unordered list. You can read more about it in the CSS Tricks almanac: https://css-tricks.com/almanac/selectors/a/after-and-before/.

Finally, I'll be using the data attribute for layout styles in later chapters. So, understanding the following will be necessary (including what the symbols ^, *, and ~ do):

[data-layout~="grid"] .portfolio-image { width: 100%; height: auto; }

Pseudo-selectors and pseudo-elements allow a great amount of control over your CSS, and also allows much more semantic markup.

Programming

I love programming! Did I mention that? Any day that goes by that I don't get to write some proper code or work on a problem that makes me scratch my head for at least 30 seconds is a sad day for me.

You don't have to be that extreme about it. However, whether it's Sass, JavaScript, PHP, ASP.NET, Ruby, or Python, it's important that you understand what we'll call the fundamentals of programming. To keep on the topic of Sass, as long as you can write a function and a mixin and use if/else statements, then you understand enough to follow along with what I'll cover.

The command line

For brevity, I'm only going to call it the command line from now on. So, regardless of your OS (Windows, Linux, or Mac), whether you use the terminal, Powershell, Cygwin, Babun, or plain old cmd.exe, when I say command line, you know what I mean.

If you don't know what I mean, then you'll need to brush up your command-line skills. I won't be using any software to compile or watch files and folders. We'll be using Sass and Compass mainly from the command line. I'll also be creating directories and files occasionally from the command line, and navigating around our project within the command line. We'll also be using Gulp from the command line a lot in later chapters.

When I'm working the command line, I prefer not to have to jump in and out of it to create folders and files. It's faster to just leave the mouse alone for as long as possible and keep typing. With practice, I'm sure you'll agree (hopefully, you already do).

So I'll quickly mention a few commands I often use so you'll know what I'm doing when you see them.

Windows and Unix users

To change into a directory (assuming you are in the documents folder, which contains a folder called my-projects), use the following command:

cd ./my-projects

Or simply use the following command:

cd my-projects

To create a directory, use the following command:

mkdir mastering-sass

Note

It's important to note that the Unix terminal is case sensitive, while Windows cmd is not.

We could also have combined those commands on one line using the and operator, &&, which I used earlier in this chapter:

cd my-projects && mkdir mastering-sass

You should now have a folder structure like this:

documents |-- my-projects |-- mastering-sass

To move up one directory (or out of the current directory into the parent directory), use the following command:

cd ..

Or you can use this command:

cd ../

To move up two directories, use this command:

cd ../../

Tip

Another great way to quickly cd into a folder is to type cd followed by a space and then simply drag the folder you want to change into onto your command line. The full path will be instantly pasted into your command line so you only need to hit Enter. This works on Unix and Windows. Hooray!

Windows

We will discuss some useful command-line tips in this section.

The quickest way to open the cmd.exe command line in Windows from XP upwards is as follows:

Press the WinKey + R, which will open the Run... dialog.Then simply type cmd and hit Enter.

The second tip that can be used is as follows.

Have you ever been in a folder and wanted to just open up the command line to be in that folder, without needing to copy the path, and right-click on the command line and go to Edit | Paste...ugh! It's actually really simple.

Hold down the Shift key and right-click in the window. Now the context popup will have an extra option, Open command window here.

You could even just hold down Shift, right-click, and then press W if that's still too much.

Why is this hidden by default? I wish I knew.

On the flip side, I bet there's been times you've been in the command line and wanted to simply open the File Explorer window in the current directory. To do that, simply type explorer and hit Enter.

To view files and folders in the current directory, use the following command:

dir

To create a file in the current directory, use this command:

notepad index.html

Note

This will create a file if that file doesn't already exist, or it will open existing files in Notepad. When creating a file, you will have to click Yes to allow Notepad to create a file and then Save from within Notepad. It's not as nice as the Unix touch command or nano, but it's there if you need to create a file quickly. It's still quicker than opening another program, saving finding the right folder, and typing the name and perhaps having to choose an extension.

Unix (Mac and Linux)

To list files and folders in the current directory, use this command:

ls

To list all files and folders, including hidden files and folders (such as .htaccess, .git, .DS_Store), use this command:

ls -a

List files and folders with metadata such as file owner, timestamps, and file permissions using the following command:

ls -l

You can even combine them to show you everything, including hidden files and all meta data, as follows:

ls -la

To create a file, use this command:

touch index.html

To edit an existing file, use this command:

nano index.html

You know your command line

You made it! Nice! So those are the things I do most from within the command line. Moving around, looking at things, and creating folders and files. So if you can also do all of those things comfortably, you'll do just fine.

Summary

So, we should now be pretty much on the same page regarding what we need installed and what concepts we'll need to get the most from the next few chapters. The good thing is that by doing the installations and setup at this early stage, we can focus on Sass and Compass and all the fun stuff from now on.

In the next chapter, we'll get started with writing some Sass. That is, of course, why we're all here. We'll take a look at the Sass documentation and how to filter through it all to get to the most important and useful features in the order you'll most likely need them.

Chapter 2. Sass – The Road to Better CSS

In this chapter, we will cover:

Setting up a simple project based strongly on typography.We'll look at using Sass from the command line and the various options we can pass to take control of our output.We'll then set up our project's configuration variables using !default to allow easy overriding in future. These variables will control all of our functions and mixins and will allow the end user to have full control of our Sass library, without needing to touch mixins or functions.We'll look at writing a small but flexible library of functions and mixins that will deal with setting up a base typography style for our default body, text, and headings. This will be based around the optimal reading line length of 60-80 characters while keeping our font sizes and line heights uniform even when we change font families.We'll write functions and a mixin to handle the output of our headings and keep the best font sizes and line heights for each heading for sans and serif.We'll then look at using lists and nested lists to reduce repetition in our mixins. We'll look at tackling one problem with two different loops and the pros and cons of both approaches.Finally, we'll go back over all of our functions and add some much needed error handling by using @error and @warn.

A bit of sassy reminiscing

As I mentioned I started Sass some time ago. I even remember that illustration of the girl with the telephone. Remember her? I always imagined she was having a sassy debate with her friend about the latest web design trends and telling her friend to stop using IDs in her CSS.

Anyways, I can also remember it was actually pretty difficult to learn Sass. The only thing that got me to persevere was I could use as little as I wanted in the beginning, so I had that safety net of plain old CSS. So when I started out I really only used Sass for the variables, imports and the nesting. Even with that, it made my life so much better!

The version was Classy Cassidy(3.0.18), and even though Sass hadn't been offering the .scss syntax for long at that point, it was really starting to make waves, due to the fact you could just write css and use as little or as much of Sass as you wanted. When it's put like that to someone you'd wonder why it wasn't a feature in the first place.

Back then you actually didn't even install Sass, you installed Haml. Sass just sort of came with it, like a cool sibling. The whole Haml situation confused me. I wasn't quite sure if I had to use it use Sass, or what the heck Haml was in the first place. Also, back then I was still pretty green to programming and definitely to the command line. The fact that the documentation was geared towards Unix completely threw me off. I wasn't even sure if I could get Sass set up on Windows properly.

I also made the mistake of thinking the Sass reference was written in a strict order. So I spent hours trying to wrap my head around the Sass::Plugin options, thinking I needed to set those up first somewhere to get things going. I didn't really know any better.

So I want to help you avoid the mistakes I made along my journey through Sass, and make sure you're getting the best out Sass. Not just the advanced features, but also the simple ones that you may have missed. You have Sass all set up and ready to go so you probably want to set up a project and start writing some Syntactically Awesome Style Sheets (Sass).

Setting up our project

You're probably eager to start writing some Sass, so let's jump right in. I'm going to create my project in my root (C:/) directory, but you can place your project wherever is easiest for you. I'll call it mastering-sass and inside I'll create the following files and folders in that folder: sass and index.html and within the sass folder create a file: style.scss.

Open your index.html file in your editor of choice and add the following markup:

<!-- mastering-sass/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Mastering Sass: Chapter 2</title> <link href="css/style.css" rel="stylesheet"> </head> <body> <div> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6</h6> <p>This is a normal paragraph of text with <em>emphasised</em>, <strong>strong</strong> text and, of course, a <a href="#">link.</a></p> <p> <img src="http://placehold.it/300x200" alt="Image from Placehold.it" style="float:left;"> !!!ENTER SOME LOREM IPSUM OR SOMETHING HERE!!!</p> <p><img src="http://placehold.it/800x600" alt="Image from Placehold.it" style="float:right;"> !!!ENTER SOME LOREM IPSUM OR SOMETHING HERE!!!</p> <ul> <li>List Item 1</li> <li>List Item 2</li> <li>List Item 3</li> <li>List Item 4</li> </ul> </div> </body> </html>

Believe it or not, this simple page has pretty much all the elements you need to make a fully functional HTML website (as it was originally intended). Not counting the stuff in the <head> or the <body> tag, there's roughly 15 elements present in almost every webpage since the dawn of web time (circa.1991), and you're looking at them.

From these elements you can make navigation, break things into sections (with more divs of course) and get pretty much any message across to a reader that text and images will allow.

Sass

You noticed the link to the stylesheet located at css/style.css. You also surely noticed we never created that. Let's open up our command line and change directory to our mastering-sass folder.

Now in your command line simply run the following command:

sass --watch sass:css

This command will tell sass to compile all sass files in the sass directory into css files in the css directory. If the folder or the files don't exist sass creates them. Once it's finished it will watch the sass directory for any changes and automatically compile them to the css directory. The command line should look something like the following screenshot:

Note

If you're wondering what the style.css.map file is all about, don't worry, we'll cover that in Chapter 7, Sourcemaps – Editing and Saving in the Browser.

So now open style.scss and we'll begin writing some Sass to style our typography. In style.scss