views:

89

answers:

1

Using sass, how do you style

#box1 img, #anotherbox img { height: 80px }

? Is using mixins the only way?

+3  A: 

One way is to list your selectors just as you have done in CSS: but that's not the Sassy way to do it since these elements don't necessarily relate to each other, so why should they belong together? They just happen to share some common styles. Listing them together like this works fine, but is slightly harder to keep organized as you add more:

#box1 img, #anotherbox img
  height: 80px

You could of course use a mixin for that if you want to generalize it:

=shorty
  height: 80px

#box1 img, #anotherbox img
  +shorty

But it's the same thing: #box1 and #anotherbox want to be in different parts of the file. You need them to share some common styles, but it makes more sense to keep them organized with the group of box rules to which they belong so you split them up:

=shorty
  height: 80px

#box1
  img
    +shorty

#anotherbox
  img
    +shorty

Since that calls the mixin twice, it creates duplication in the output:

#box1 img { height: 80px }
#anotherbox img { height: 80px }

This is perfectly acceptable when the mixin just has a few rules in it, or when it's used in a limited number of places. (Mixins really come into their own when the mixin generates different style rules based on parameters.)

Ok, so that's the trip around the block with mixins.

Here's how you avoid that duplication using @extend:

The idea of @extend was originally proposed by Nicole Sullivan in her CSS Wish List blog post. This seemed like such a good idea that an implementation in current plain CSS was devised, and it was added to Sass shortly thereafter.

If your style rules describe a pattern that's intended to be used as a general class or a base style for a number of other items, you should consider @extend.

To understand the difference, we know a mixin will output the styles each time it's called, but extend will instead create a list of all the selectors where that style is used, and then attach them to one style block:

.thumb-size
  height: 80px

#box1
  img
    @extend .thumb-size

#anotherbox
  img
    @extend .thumb-size

Produces:

.thumb-size, #box1 img, #anotherbox img { height: 80px }

It will print the base style class (.thumb-size) in the output, even if you strictly don't need it for anything else. But, I think this is preferable anyway since it defines the purpose of that list of selectors when it's sitting in front of them.

Andrew Vit
I used the SASS syntax here, but it works the same if you prefer the CSS-lookalike SCSS syntax with {curly braces} instead.
Andrew Vit