Creating Custom Modifiers

Fran Dios
The Web Tub
Published in
2 min readJun 6, 2017

Onsen UI provides native-like styles for all the UI components that presumably work for most of the situations. However, sometimes we want to give our apps a personal touch in the shape of custom styles or animations. Let’s learn how to quickly implement custom “modifiers” to alter the style of our components in this article.

About “modifier” attribute

Every visual component in Onsen UI accepts a modifier attribute that alters its style. Modifiers are a cross-component way to provide visual customizability. A modifier is translated into a set of CSS classes not only for the own element but also for its children. This way, we don’t need to set CSS classes manually for every child element of our UI component or provide complex CSS selectors.

For example, using material modifier in ons-input element automatically sets .text-input--material and .text-input--material__label to its children, whereas underbar modifier sets .text-input--underbar and .text-input--underbar__label.

In order to see how any element sets these classes, you can have a look at the scheme object on each element’s declaration. For example, an ons-back-button‘s scheme looks like this. This means it will apply .back-button--modifier to the element itself and .back-button--modifier__icon and .back-button--modifier__label to its corresponding children.

Custom modifier

Let’s see a simple but useful example of how to create a custom modifier for one of our recent components, ons-toast.

By default, ons-toast is displayed full-width at the bottom of the page. Let’s change it!

We simply need to check the DOM and play a bit with the CSS properties. With this simple CSS, we can make a right-aligned “danger” modifier:

Or a centered and rounded “success” modifier:

And an extra modifier to change the font:

.toast--thick__message, .toast--thick__button {
font-weight: 700;
}

Now we can apply all of this with a simple modifier="danger", modifier="success thick" or any other combination.

Check the result here.

For notifications, it is also possible to specify modifiers with the inline method:

In case we only want to apply a specific modifier for a specific platform, we can use :not selector. For example, let’s say we want to exclude the material modifier for iOS, we can with :not selector as shown below:

.toast--onlyios:not(.toast--material) {
/* Only works when 'material' modifier is not applied */
}

Similarly, only for Android:

.toast--onlyandroid.toast--material {
/* Only works when 'material' modifier is applied */
}

Onsen UI is an open source library used to create the user interface of hybrid apps. You can find more information on our GitHub page. If you like Onsen UI, please don’t forget to give us a star! ★★★★★

--

--

Fran Dios
The Web Tub

I create apps from Tokyo with love. I also like tomatoes.