Fireship · @fireship
Ionic 4 Theme Builder with CSS Variables
Uploaded August 15, 2018 · Length 12:12
Summary
Learn how to build a dynamic theme generator with CSS variables in Ionic 4, allowing users to change colors and animation speed on the fly.
- ionic 4
- css variables
- theme generator
- angular service
- css animation
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
One of the coolest things about Ionic 4 is that it uses CSS variables. Over the next few minutes,
- 0:11
you'll learn everything you need to know about CSS variables, how they're used in Ionic, and we'll
- 0:16
build this dynamic theme generator from scratch that allows users to change the colors on the fly
- 0:20
and also change the behavior of CSS animations. If you're new here, like and subscribe,
- 0:26
And I also want to let everybody know that I'm working on a brand new course for Ionic
- 0:29
4 and Firebase from scratch.
- 0:31
If there's anything you want to see in that course, leave me a comment below and it will
- 0:34
cover some pretty advanced concepts that you won't see anywhere else.
- 0:37
And it'll be free to all pro members when it comes out in the next week or two.
- 0:41
The thing that makes CSS variables special, as opposed to variables in SAS or less, is
- 0:46
that they can be interpreted by the browser on the fly.
- 0:50
So that means we can use JavaScript to change global CSS variables and get different styling
- 0:55
in the UI.
- 0:56
As you can see here, when I click a button we get an entirely different theme with different
- 1:00
shade colors for all the different components in the app.
- 1:03
So let's go ahead and start with the absolute basics and just look at what CSS variables
- 1:07
are.
- 1:08
I've generated a new Ionic 4 app and then I have it opened here in VS Code.
- 1:12
You'll notice a theme directory inside the source directory that has all of our global
- 1:16
CSS variables.
- 1:18
You'll notice that they're defined with this root selector.
- 1:21
That just gives them a global scope, meaning that all elements in the DOM can use them,
- 1:25
including any web components that also use the shadow DOM.
- 1:29
In Ionic 4, all of the components are just web components that use the shadow DOM, so
- 1:33
global variables like this are a really easy way to style them.
- 1:38
But it's really important that you understand that variables like this can cascade just
- 1:41
like normal CSS styles.
- 1:44
So let's imagine we define a global CSS variable inside of a button instead of the root.
- 1:50
In this case we're overriding the ionColorPrimary variable.
- 1:54
Now the button and all of its children elements will inherit the red color, but everything
- 1:58
else that's not a button or a child of a button will still inherit the global one that


