Mastering Sass
上QQ阅读APP看书,第一时间看更新

Three things you should know about lists

Here are three important things you should know about lists:

  • Sass list indexes DO NOT start at zero
  • You can separate the items in a list with spaces instead of commas
  • You can even leave out parentheses

Let's dive deep in the preceding mentioned points.

Sass list indexes do not start at zero. Some of you who've dealt with arrays in most languages will be expecting to get a value of $h3-font-size with the preceding code. However, Sass lists are not 0 based. Their first index is, in fact 1, meaning we can use the number that makes sense (to people who don't do a lot of programming) and not be required to subtract 1 from our heading variable first.

You can separate the items in a list with spaces instead of commas. This is means we could have written our list like this instead:

$headings: ($h1-font-size $h2-font-size $h3-font-size $h4-font-size, $h5-font-size $h6-font-size); 

One thing to be very careful of when using space separated lists, is using strings. If you don't quote your strings, Sass will interpret each word as an item in the list:

$sentence: (This is a sentence obviously); 

Instead of one item, This is a sentence obviously, we would instead have 5 strings:

content: nth($sentence, 4); // Would be the string: content: sentence 

Worse, if you put the grammatically correct comma in that sentence...

$sentence: (This is a sentence, obviously); 

You would in fact make two separate lists and checking for the 4th item would cause an error.

For this reason, you should always quote your strings! I would argue you should quote your strings even when you don't expect to be dealing with lists. The fact is, you can't be certain your functions or mixins will not be passed through another function or mixin which uses lists. Therefore, the safest bet is to always quote your strings.

Let's get even weirder. If you thought leaving out commas was strange, how about then leaving out the parentheses. That's right, you can leave out commas and parentheses! This is similar in a way to CSS shorthand:

padding: 10px 0 5px 5px; 

For this reason, I'm ok with leaving out commas and parentheses, and as long as you quote your strings Sass will do a good job of figuring everything out. I would advise you simply be consistent. I'm used to using parentheses and commas in other languages so I continue to do so in Sass. Not because I don't like the idea of less typing, simply because when I go back to PHP or JavaScript I won't all of a sudden forget to write commas in my arrays.