Dynamic Styling in Vue.js: Inline CSS

malgamves profile image Daniel Madalitso Phiri ・2 min read

If you know me, you know I like Vue.js fro some reason, I don't hide my love for it's simplicity and elegance. I almost always learn something super cool that you can do with it. You know - developers, always learning. Today in my Vue adventures, I'm sharing a brief into to dynamic styling.

I was putting together a project and thought, "Wouldn't it be cool if we could change background colours dynamically by injecting a JavaScript data object into CSS?" - sort of.. A few google searches later I came found that Vue.js supports this.

In the official Vue.js Documentation, it's referred to as Class and Style Bindings

Have a look ✨

Please don't shame me for my crappy CSS, I really had to put this together quick πŸ˜–

Anyways I think it's a pretty cool way to do styling for some very specific use cases.

  • Animating buttons for user actions
  • Highlighting fields to emphasize a certain flow
  • Customizing user display options

In my example, I used inline CSS to change the styling of tags. You could change the font size, text decoration or colour. In theory as long as it is a CSS property, Vue can change it dynamically. If you look through the CodeSandbox code, you notice a couple of data properties - textSize,textColor and textDec all interpolated into some inline CSS as a reference value for specific CSS properties and that's it. Super fun.

Note: CSS has uses kebab case (font-size) and that throws errors for inline styling. Vue lets you use the camel case equivalent (fontSize) to style things dynamically just in case you get into some trouble.

We can keep adding a bunch of inline CSS with the data properties but it's messy and does make the most readable code ever. So lets over complicate things (jokes) and go for CSS classes! Hopefully they'll be cleaner.

Just as we did for styling, we can bind classes to HTML in. We'll do that next time with hopefully much better CSS and more real world examples. Let me know if you try it and how it works out for you.

Posted on by:

malgamves profile

Daniel Madalitso Phiri


Tech x Culture - Tech Writer - Disk Jockey - Host #RushingFwd - @devcon_zm, @CodeCastZM - Prev. @HasuraHQ - Int'l Speaker - Zambian πŸ‡ΏπŸ‡² #DevRel


markdown guide