How to add new colours to Tachyons

November 2018

I'm a big fan of functional css; Tachyons in particular. Declarative styles make working on large, ongoing projects much simpler.

Tachyons comes with a bunch of default colours, but inevitably, you'll need to define new ones. It's possible to define custom colours with the Tachyons generator. However using the generator isn't always convenient, particularly for existing projects.

To solve this, I use a Sass function which generates colour classes, separate from the core Tachyons framework.

// _colours.scss

$colours: (
  'off-white': #F9F9F9,
  'mint-green': #EFF9E6,
  'yellow': #ffdd60,
);

@each $name, $hex in $colours {
  .#{$name} {
    color: $hex;
    &:visited {
      color: $hex;
    }
  }
  .bg-#{$name} {
    background-color: $hex;
  }
  .b--#{$name} {
    border-color: $hex;
  }
  .hover-bg-#{$name} {
    &:focus,
    &:active,
    &:hover {
      background-color: $hex;
    }
  }
  .hover-#{$name}:hover,
  .hover-#{$name}:visited:hover {
    color: $hex
  }
}

This spits out utility classes to use in your markup.

// Output
.off-white {
  color: #F9F9F9;
  &:visited {
    color: #F9F9F9
  }
}
.bg-off-white {
  background-color: #F9F9F9;
}
.b--off-white {
  border-color: #F9F9F9;
}
.hover-bg-off-white {
  &:focus,
  &:active,
  &:hover {
    background-color: #F9F9F9;
  }
}
.hover-bg-off-white:hover,
.hover-bg-off-white:visited:hover {
  color: #F9F9F9;
}
// ... repeat for .mint-green, .yellow etc

Ever wish you got more email?

Neither do I. You're busy, and so is your inbox. I'll only be in touch when I publish something new. And of course it goes without saying your email will be kept completely private.