Customising Ionic with Sass

In a previous post, I wrote about using generator-ionic to create the scaffolding for a mobile-optimised Administration UI. In this post, we'll update the scaffold in order to add support for Sass customisation.

generator-ionic

Although the generator asks if you would like to use Sass (with Compass), there are a few additional steps we need to complete:

  • Create variables.scss
  • Create styles.scss
  • Update main.scss
  • Update index.html

Create variables.scss

Ionic's variables are defined in app/bower_components/ionic/scss/_variables.scss. We need a place to override Ionic's variables and to define our own project specific variables, app/styles/variables.scss:

...

// Ionic variables to override
$calm:           #11c1f3 !default;
$balanced:       #9FBB58 !default;

// Vardyger variables
$vardygerOrange: #ff9900 !default;

...

Note: Add !default to all variables so that they can be overridden later on if necessary.

Create styles.scss

We also need a place to define any project specific styles, app/styles/styles.scss:

...

p {
  margin: 0 0 ($line-height-computed / 2);
  font-weight: $body-font-weight;
}

small {
  font-size: 60%;
  font-weight: $small-font-weight;
}
  
...

Update main.scss

The generated app/styles/main.scss is empty, we need to update it as follows:

@charset "UTF-8";

@import "variables";

@import "../bower_components/ionic/scss/ionic";

@import "styles";

First, we need to @import variables.scss (where we override Ionic's variables and define our own project specific variables). Then, we need to @import ionic.scss (Ionic's core Sass file). And, finally we need to @import styles.scss (where we define our project specific styles).

Update index.html

The generated app/index.html:

...

<!-- build:css styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/ionic/release/css/ionic.css" />
<!-- endbower -->
<!-- endbuild -->
<link href="styles/style.css" rel="stylesheet">

<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="styles/ionic.app.css" rel="stylesheet">
-->

...

Grunt will compile main.scss to generate styles/main.css, so we need to update app/index.html as follows:

...

<link rel="stylesheet" href="styles/main.css" />

...

We can use Ionic Lab:

grunt serve --lab

To quickly see how the application looks on both iOS and Android:

Ionic Lab will apply the .platform-ios and .platform-android styles to Ionic's UI components.

If you don't have the time to create your own theme then take a look at these third-party Ionic framework themes.

Note: The scaffolded Grunt file is configured to compile any .scss files in the app/styles directory, which means you may need to use grunt serve --force (or add @import "variables"; to your project's styles.scss).

References: