开发者

Using sass, how do you style "#div1 img, #div2 img { height: 80px }"?

开发者 https://www.devze.com 2023-01-03 09:22 出处:网络
开发者_C百科Using sass, how do you style #box1 img, #anotherbox img { height: 80px } ?Is using mixins the only way?One way is to list your selectors just as you have done in CSS: but that\'s not t
开发者_C百科

Using sass, how do you style

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

? Is using mixins the only way?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消