Reader small image

You're reading from  Sass and Compass for Designers

Product typeBook
Published inApr 2013
Reading LevelBeginner
Publisher
ISBN-139781849694544
Edition1st Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Ben Frain
Ben Frain
author image
Ben Frain

Ben Frain has been a web designer/developer since 1996. He is currently employed as a UI-UX Technical Lead at bet365. Before the web, he worked as an underrated (and modest) TV actor and technology journalist, having graduated from Salford University with a degree in Media and Performance. He has written four equally underrated (his opinion) screenplays and still harbors the (fading) belief he might sell one. Outside of work, he enjoys simple pleasures: playing indoor football while his body and wife still allow it and wrestling with his two sons.
Read more about Ben Frain

Right arrow

Chapter 7. Easy CSS3, Image Sprites, and More with Compass

Throughout the earlier chapters, we have used Compass lightly and sporadically. Although we used a number of Compass's amazing color features (such as tint and shade) in Chapter 4, Manipulate Color with Ease, we haven't explored the 'meat and potatoes' of what I feel makes Compass so useful.

Some of the most impressive and time-saving benefits of using Compass are its plethora of mixins for generating cross-browser experimental CSS styles. If that wasn't enough, Compass can also perform voodoo tricks such as automatically creating image sprites and data URIs from separate images.

In this chapter we are going to apply a whole load of Compass mixins and helpers to our http://sassandcompass.com project. Hopefully, this chapter should also serve as a handy reference for the syntaxes you'll need when using the most common Compass mixins day-to-day.

In this chapter, we will:

  • Learn the Compass syntaxes for CSS features including box-shadow...

Easy CSS3 with Compass's mixins


Compass has gained fast and fervent favor with developers as it enables authors to write a mixin using a single syntax that, on compile, generates a full vendor-prefixed 'stack' of properties in the CSS. This has been particularly useful with experimental CSS properties, often referred to in recent years as CSS3.

Tip

CSS actually gets developed in modules so it is often possible that some modules are further along than others. Selectors, for example, is already a level 4 working draft specification: http://www.w3.org/TR/selectors4/.

Let's look at some of these common experimental properties and how we can produce cross-browser code with a relevant Compass mixin.

First up, text-shadow.

The text-shadow syntax

Text shadow is actually well supported in all modern browsers (Internet Explorer 9 being a notable exception), so Compass won't generate a vendor-prefixed stack for it (it's smart enough to know it isn't needed). Despite this, let's use a Compass mixin to include...

The border-radius syntax


Border-radius is another CSS property that's finally settling down and being implemented sans vendor prefix in modern browsers. Regardless, to ensure the widest compatibility, use the Compass border-radius mixin. Here's an example:

@include border-radius(5px);

This applies the same radius to every corner of a box. We can set a variable as the default for the border-radius like this:

$default-border-radius: 5px;

Let's add that into our _variables.scss partial and then we can just include a rounded corner on an element like this:

@include border-radius;

That's fine when we need the same radius on every corner, but let's consider how we specify different radiuses for each corner:

@include border-top-right-radius(5px);
@include border-bottom-right-radius(5px);
@include border-bottom-left-radius(5px);
@include border-top-left-radius(5px);

Or, you can specify two continuous corners at once like this:

@include border-top-radius(5px); // top left and top right
@include border-right...

Multiple columns


The CSS Multi-column Layout Module (http://www.w3.org/TR/css3-multicol/) specifies how an author can display content within an element across a number of columns. Compass has a mixin to produce the necessary cross-browser code. I'll be honest, this isn't something I use very often (with large amounts of text you have to scroll down and then back up to carry on reading which feels wonky), but it's nice to have regardless. We'll add an HTML class to the second paragraph of our markup and then use this mixin:

.two-cols {
  @include column-count(3);
}

Here is the effect in the browser:

We can amend this further by adding in a dividing rule like this:

.two-cols {
  @include column-count(3);
  @include column-rule(1px, dotted, lighten($color10, 84%));
}

Column rule syntax

The syntax for the arguments of the column rule mixin are the same as a CSS border; first the width of the dividing line, then the type of line, and finally the color, each separated with a comma.

Here is the effect...

Background gradients


If you've dealt with background-gradients for any length of time, you'll know there was a time of madness where we needed to write gazillions of different syntaxes in the CSS to ensure cross-browser compatibility. Thankfully, Compass lets us write one mixin with a single syntax and it produces all the necessary CSS to make browsers happy. Let's use this to spruce up the main header area. Currently we have a solid background color and a border below. Let's remove this and instead use a single background gradient and box shadow. Here are the two mixins being used:

@include background(linear-gradient(to bottom, darken($color-pink, 10%) 0px, darken($color-pink, 10%) 4px, lighten(complement($color-pink), 10%) 4px,  complement($color-pink) 100%));
@include box-shadow(#ccc 0px 3px 10px);

Here is how that looks in the browser:

Background linear-gradient syntax

I'm aware that with all the color functions in that prior chunk of code, the background mixin syntax looks a little crazy...

Adding background images with the Compass image-url helper


With CSS, when you want to use a background image, it's usually necessary to provide the relative path to the image from the CSS. Here's an example:

background-image: url("../img/amazon-com.svg");

If you're anything like me, there's often a 'hunt the image path' game that happens on a new project, caused by trying to figure out and set the correct path to the image. For example, is the path to the images ../img/, ./img, /img, or just img? Thankfully, with Compass the image-url helper has us covered. Remember back in Chapter 2, Setting Up a Sass and Compass project, we looked at the config.rb file. One of the configuration options we set was this:

images_dir = "img"

This lets us target images for backgrounds easily from within our Sass files, no matter where they are in our project. It doesn't matter whether a style is buried in a partial file three 'levels' away from the image, we can still just do this:

background-image: image-url(...

Image width and height helpers


There are also a couple of image helpers for automatically determining an image's height or width. Therefore, as long as we're not using SVG images (as they are vector-based they can have indeterminate dimensions), we can use these helpers to automatically get and set the height and width of appropriate CSS properties:

.buy-amazon-uk {
  display: block;
  background-image: image-url("amazon-co-uk.png");
  background-size: image-width("amazon-co-uk.png") image-height("amazon-co-uk.png");
  background-position: 50% 50%;
  background-repeat: no-repeat;
  height: image-height("amazon-co-uk.png");
  width: image-width("amazon-co-uk.png");
}

In this example, we are using these helpers to not only set the background-size property but also set the image width and height. Here's the relevant CSS that compiles to:

.buy-amazon-uk {
  background-image: url('../img/amazon-co-uk.png?1357598801');
  background-size: 223px 50px;
  background-position: 50% 50%;
  background-repeat...

Compass image sprites


While we can set the background images for elements with the help of Compass image helpers for individual images, it's often considered a better practice to use an image sprite. I'm sure you'll have used this technique before. A single image (referred to as an 'image sprite') is created that includes all the other images. This single image is then shifted around by the CSS background-position property to show different images on different elements. The technique has an additional benefit of using images for hover states. As the single image is already loaded, there's no delay when an item is hovered over (the delay is usually caused by the separate hover image being requested, fetched, and parsed).

It's a great technique but not without some headaches, principally, working out the background positions for each image. Well, guess what? Compass can take care of all this and more. I hope you're sitting down. This is quite simply brilliant.

We will use this technique to set...

Compass's text replacement mixins


Compass has a few mixins to help deal with occasions when you want to hide text. Let's look at some of those.

The hide-text mixin

The first one we'll look at is the hide-text mixin. This is how it looks:

@include hide-text;

Here's an example of how you would use it:

.hide-text {
  @include hide-text;
}

Here's the CSS it produces:

 .hide-text {
  text-indent: -119988px;
  overflow: hidden;
  text-align: left;
 }

Now, that certainly gets the job done. If the @include hide-text mixin is added to the ir selector, it shifts the text accordingly. However, be aware that to do this, the browser is painting a box with the text in 119988px off the screen. That's not really an issue on desktop machines but it may be on mobile devices. Some alternative techniques are listed as follows, however, for now, here is the effect in the browser:

The squish-text mixin

Compass also has a mixin called squish-text to squish text inline if you want it to be visually hidden but still accessible...

Creating data URIs from images


One problem with PNG-based image sprites is that they are not resolution independent. With more and more HiDPI devices (Apple gives their HiDPI devices the 'retina' moniker) coming onto the market, that necessitates us creating at least two sprites to cover normal and HiDPI devices. That situation will only get worse as higher and higher DPI devices enter the market and I, for one, don't like repetitive work!

Furthermore, the spriting technique we have already looked at doesn't play particularly well with responsive designs (as currently, the Compass image sprite engine uses pixel-based, rather than proportional, positioning) so they have fallen out of favor with me of late.

Instead, where possible, I opt for SVG images. As their name implies, (Scalable Vector Graphics—you knew that already though, I know) SVGs are entirely scalable and look incredibly sharp on all devices, regardless of pixel density.

Tip

Wondering how to produce SVGs? Adobe Illustrator handles...

Easy fallbacks for non-SVG capable devices


Thanks to the Sass parent selector we've already learned about in Chapter 3, Understanding Nesting, Extend, Placeholders, and Mixins, remember that it's easy to create fallbacks in tandem with Modernizr for different device capabilities. For example, although opting for SVGs as default, we could provide a fallback to equivalent PNG graphics, like this:

.buy-amazon-us {
  background-image: inline-image("svg/amazon-us.svg");
  .no-svg & {
    background-image: image-url("png/amazon-us.png");
  }
}

Note

Bet on SVG!

SVG is currently an underused technology on the Web, but there are is a host of exciting features hopefully coming to it in the near future, fragment identifiers (http://www.broken-links.com/2012/08/14/better-svg-sprites-with-fragment-identifiers/) being but one example.

CSS transforms


Compass has a mixin for defining any CSS Level 3 transform.

The Compass 2D transform mixins follow exactly the same syntax as the W3C 2D Transform Functions (http://www.w3.org/TR/css3-transforms/#two-d-transform-functions).

Therefore, if we wanted to scale we could write this:

@include scale(2,2); // Make it twice original size

If we wanted to translate (translate moves an element in 2D space) we could write this:

@include translateX(20px); // Move it 20px right

For the odd occasions when you want to add multiple transforms to a single element, use the simple-transform mixin. Here's an example:

@include simple-transform(1.05,3deg);

That would scale the image by 1.05 and also rotate it by 3 degrees. The arguments must be passed in this order: scale, rotate, translate-x, translate-y, skew-x, skew-y, origin-x, origin-y. However, just remember this is only really useful for combining multiple transforms. Ordinarily, for a single transform, just use the standard transform mixins already...

CSS Filters


Compass provides a mixin to produce a vendor-prefixed stack of properties for CSS Filters. The syntax follows the W3C specification described here at http://www.w3.org/TR/filter-effects/.

Let's use the drop-shadow filter to solve our prior issue. We'll remove the existing box-shadow mixin and instead apply a CSS drop-shadow filter with the Compass mixin:

@include filter(drop-shadow(#ccc 1px 1px 0px));

And here is the effect in the browser:

Compass will let you apply all CSS filters in this manner, essentially following the W3C syntax for the relevant filter.

Tip

Be aware that filters are experimental at this stage so you may find, as in this instance, that it leads to blurring of the text. I'm therefore reverting to the rotated square with the box-shadow technique we used before.

Transitions


One final Compass mixin to share with you is the transitions mixin. It allows an easy cross-browser way to use CSS transitions. Here's an example of the mixin in action:

@include single-transition(all, .3s, ease, 0s);

Again, it follows the same basic syntax as the W3C transition syntax (http://www.w3.org/TR/css3-transitions/).

Inside the parenthesis, the first value is the property to be transitioned (all in this instance), then the duration of the transition, next is the timing method (ease in this instance), and finally the transition delay. We'll add that to the header links to make a smooth transition to the hover-based styles.

As ever, Compass provides a full vendor-prefixed stack in the CSS, here's the output of the single-transition mixin we just wrote:

-webkit-transition: all 0.3s ease;
-webkit-transition-delay: 0s;
-moz-transition: all 0.3s ease 0s;
-o-transition: all 0.3s ease 0s;
transition: all 0.3s ease 0s;

Tip

Compass will also let you deal with multiple transitions in...

Summary


In this chapter, we've used some of the many and varied helpers and mixins of Compass to significantly improve the aesthetics of our test project. We've created an image sprite, made data URIs, background gradients, shadows, and a whole lot more.

Hopefully, you are already realizing how much easier these tools and techniques can make your style sheet authoring. Remember, for the full list of Compass helpers and mixins, you can consult the Compass documentation at http://compass-style.org/reference/compass/.

In the next chapter, we'll concentrate on trying to make our existing code DRYer (a programming acronym for Don't Repeat Yourself), focusing on how we can use the programmatic power that Sass affords, to generate repetitive code more easily.

We shouldn't let words such as 'programmatic' and 'logic' worry us, though. We can totally do this!

Tip

The Compass homepage is at http://compass-style.org and you can view the reference documentation for Compass features at http://compass-style...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Sass and Compass for Designers
Published in: Apr 2013Publisher: ISBN-13: 9781849694544
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Ben Frain

Ben Frain has been a web designer/developer since 1996. He is currently employed as a UI-UX Technical Lead at bet365. Before the web, he worked as an underrated (and modest) TV actor and technology journalist, having graduated from Salford University with a degree in Media and Performance. He has written four equally underrated (his opinion) screenplays and still harbors the (fading) belief he might sell one. Outside of work, he enjoys simple pleasures: playing indoor football while his body and wife still allow it and wrestling with his two sons.
Read more about Ben Frain