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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)