Nesting, Extend, Placeholders, and Mixins

0
60
8 min read

(For more resources related to this topic, see here.)

Styling a site with Sass and Compass

Personally, while abstract examples are fine, I find it difficult to fully understand concepts until I put them into practice. With that in mind, at this point I’m going
to amend the markup in our project’s index.html file, so we have some markup
to flex our growing Sass and Compass muscles on.

We’re going to build up a basic home page for this book. Hopefully, the basic layout and structure will be common enough to be of help. If you want to see how things turn out, you can point your browser at http://sassandcompass.com, as that’s what we’ll be building.

The markup for the home page is fairly simple. It consists of a header with links, navigation made up of list items, images, and content and a footer area. Pasting the home page markup here will span a few pages (and be extremely dull to read. Don’t get too hung up on the specifics of the markup.

Let me be clear. The actual code, selectors used, and the finished webpage that we’ll create are not important. The Sass and Compass techniques and tools we use to create them are.
You can download the code from the book’s page at http://packtpub.com and also from http://sassandcompass.com

You can download the code from the book’s page at http://
packtpub.com
and also from http://sassandcompass.com

At this point, here’s how the page looks in the browser:

Image

Wow, what a looker! Thankfully, with Sass and Compass we’re going to knock this
into shape in no time at all.

Notice that in the source code there are semantically named classes in
the markup. Some people dislike this practice, but I have found that it
makes it easier to create more modular and maintainable code.

A full discussion on the reasoning behind using classes against styling
elements themselves is a little beyond the scope of this book. However,
a good book on this topic is SMACSS by Jonathan Snook (http://
smacss.com). It’s not essential to adhere slavishly to the conventions
he describes, but it’s a great start in thinking about how to structure
and write style sheets in general.

First, let’s open the _normalize.scss partial file and amend the default styles for
links (changing the default text-underline to a dotted bottom border) and remove
the padding and margin for the ul tags.

Now I think about this, before we get knee-deep in code, a little more organization
is called for.

Separating the layout from visuals

Before getting into nesting, @extend, placeholders, and mixins, it makes sense
to create some partial files for organizing the styles.

Rather than create a partial Sass file for each structural area (the header, footer,
and navigation), and lump all the visual styles relevant inside, we can structure
the code in a slightly more abstract manner.

There is no right or wrong way to split up Sass files. However,
it’s worth looking at mature and respected projects such
as Twitter Bootstrap (https://github.com/twitter/
bootstrap
) and Foundation from Zurb (https://github.com/zurb/foundation) to see how they organize their code.

We’ll create a partial file called _base.scss that will contain some base styles:

code

Then a partial file called _layout.scss. That will only contain rules pertaining
to visual layout and positioning of the main page areas (the previously mentioned
header, footer, aside, section, and navigation). Here are the initial styles being
added into the _layout.scss partial file:

code

There is nothing particular to Sass there, it’s all standard CSS.

Debug help in the browser

Thanks to the popularity of Sass there are now experimental features
in browsers to make debugging Sass even easier. When inspecting
an element with developer tools, the source file and line number is
provided, making it easier to find the offending selector. For Chrome,
here’s a step-by-step explanation: http://benfra.in/1z1
Alternatively, if using Firefox, check out the FireSass extension:
https://addons.mozilla.org/en-us/firefox/addon/
firesass-for-firebug/

Let’s create another partial file called _modules.scss. This will contain all the
modular pieces of code. This means, should we need to move the .testimonial
section (which should be a modular section) in the source code, it’s not necessary
to move it from one partial file to another (which would be the case if the partial
files were named according to their existing layout).

The _module.scss file will probably end up being the largest file in the Sass project,
as it will contain all the aesthetics for the items on the page. However, the hope is
that these modular pieces of code will be flexible enough to look good, regardless
of the structural constraints defined in the _layout.scss partial file.

If working on a very large project, it may be worth splitting the
modules into sub-folders. Just create a sub-folder and import the
file. For example, if there was a partial called _callouts.scss
in a sub-folder called modules, it could be imported using the
following code:

code

Here is the contents of the amended styles.scss file:

code

A quick look at the HTML in the browser shows the basic layout styles applied:

Image

With that done, let’s look at how Sass’s ability to nest styles can help us make
modules of code.

What nesting is and how it facilitates
modules of code

Nesting provides the ability to nest styles within one another. This provides a handy way to write mini blocks of modular code.

Nesting syntax

With a normal CSS style declaration, there is a selector, then an opening curly brace,
and then any number of property and value pairs, followed by a closing curly brace.
For example:

code

Where Sass differs is that before the closing curly brace, you can nest another
rule within. What do I mean by that? Consider this example:

code

In the previous code, a color has been set for the link tag using a variable. Then
the hover and focus state have been nested within the main anchor style with a
different color set. Furthermore, styles for the visited and active state have been
nested with an alternate color defined.

To reference a variable, simply write the dollar sign ( $) and then the name of the variable, for example, $variable.

When compiled, this produces the following CSS:

code

Notice that Sass is also smart enough to know that the hex value #7FFF00 is actually the color called chartreuse, and when it has generated the CSS it has converted it to the CSS color name.

How can this be used practically? Let’s look at the markup for the list of navigation
links on the home page. Each currently looks like this:

code

I’ve omitted the additional list items and closing tags in the previous code for the sake of brevity. From a structure point of view, each list item contains an anchor link with a <b> tag and a <span> tag within. Here’s the initial Sass nested styles that have been added into the _modules.scss partial to control that section:

code

Notice that the rules are being nested inside the class .chapter-summary. That’s because it then limits the scope of the nested styles to only apply to elements within a list item with a class of .chapter-summary. However, remember that if the styles can be re-used elsewhere, it isn’t necessarily the best practice to nest them, as they may become too specific.

The nesting of the selectors in this manner partially mirrors the structure of the HTML, so it’s easy to see that the styles nested within only apply to those that are similarly structured in the markup. We’re starting with the outermost element that needs to be styled (the <li class=”chapter-summary”>) and then nesting the first element within that. In this instance, it’s the anchor tag. Then further styles have been nested for the hover and visited states along with the <b> and <span> tags.

I tend to add focus and active states at the end of a project, but that’s a personal thing. If you’re likely to forget them, by all means add them at the same time you add hover.

Here’s the generated CSS from that block:

code

The nested styles are generated with a degree of specificity that limits their scope;
they will only apply to elements within a <li class=”chapter-summary”>.

It’s possible to nest all manner of styles within one another. Classes, IDs, pseudo
classes; Sass doesn’t much care. For example, let’s suppose the <li> elements need
to have a dotted border, except for the last one. Let’s take advantage of the last-child
CSS pseudo class in combination with nesting and add this section:

code

The parent selector

Notice that any pseudo selector that needs to be nested in Sass is prefixed with
the ampersand symbol (&), then a colon (:). The ampersand symbol has a special
meaning when nesting. It always references the parent selector. It’s perfect for
defining pseudo classes as it effectively says ‘the parent plus this pseudo element’.
However, there are other ways it can work too, for example, nesting a few related
selectors and expressing different relationships between them:

code

This actually results in the following CSS:

code

We have effectively reversed the selectors while nesting by using the & parent
selector.

Chaining selectors

It’s also possible to create chained selectors using the parent selector. Consider this:

code

That will compile to this:

code

That will only select an element that has both HTML classes, namely selector-one
and selector-two.

The parent selector is perfect for pseudo selectors and at odd times its necessary
to chain selectors, but beyond that I couldn’t find much practical use for it, until I
saw this set of slides by Sass guru Brandon Mathis http://speakerdeck.com/u/imathis/p/sass-compass-the-future-of-stylesheets-now. In this, he illustrates
how to use the parent selector for nesting a Modernizr relevant rule.


Subscribe to the weekly Packt Hub newsletter

* indicates required

LEAVE A REPLY

Please enter your comment!
Please enter your name here