Read more

Sass: How to do math with shorthand values inside variables

Arne Hartherz
August 31, 2016Software engineer at makandra GmbH

If you need to modify (e.g. add 2px) a Sass variable that defines multiple values as one (e.g. for short-hand CSS definitions such ass padding), you can by using nth. It's ugly.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

While you could split up such variables into multiple values (e.g. combined padding into one for vertical and one for horizontal padding) in your own Sass definitions, when using some framework definitions like bootstrap-sass, those variables are defined outside your reach.

The following is helpful if you really want to use values from such variables. However, for readability, consider simply copying over those values (as they probably will not change in a long time / ever) and adding a Sass comment about the variable your values are based on.

Example

Consider some default padding for UI tabs that you want to increase.

$pad: 10px 15px

.tab
  padding: $pad + 2px // WRONG

That will incorrectly concatenate both:

.tab {
  padding: 10px 15px2px; // WRONG
}

Fun fact: Multiplication (like $pad * 2) will even cause an error:

Undefined operation: "10px 15px times 2".

However, using nth, we can access individual values:

$pad: 10px 15px

.tab
  padding: (nth($pad, 1) + 2px) (nth($pad, 2) + 2px)
.tab {
  padding: 12px 17px;
}

Still, this is ugly and you might just be fine copying and pasting. But don't tell anyone.

Posted by Arne Hartherz to makandra dev (2016-08-31 11:27)