Tuesday, October 11, 2016

Ionic 2 - Using predefined colors

Today I wanted to style a list, in which one item could be selected. Such an selected item should have the primary color.

This meant mainly, I had to define a css class, which I assigned to a selected item:
.selected {
  background-color: #387ef5;
  color: #fff;
}
The background-color is the primary color. And as color, I chose something with a good contrast.

However, this approach is not very flexible. After all, Ionic provides SASS variables. So, why not use them?

Well, one reason could be, that the documentation is not complete. But finally, I made it:
  • The color values are defined in src/theme/variables.scss. You find there something like
    $colors: (
      primary:    #387ef5,
      secondary:  #32db64,
      danger:     #f53d3d,
      light:      #f4f4f4,
      dark:       #222,
      favorite:   #69BB7B
    );
  • For using a color value, Ionic provides a SCSS function named color() (defined in node_modules/ionic-angular/themes/ionic.functions.scss):
    .selected {
      background-color: color($colors, primary);
      color: #fff;
    }
  • For the text color, there is a similar function called color-contrast():
    .selected {
      background-color: color($colors, primary);
      color: color-contrast($colors, primary);
    }
  • If you want more control about the contrast color, you can define it by yourself in the color map, e.g.:
    $colors: (
      primary:    (base: #387ef5, contrast: #ff0000),
      ...
    );
    Now the text is red instead of white.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.