Dynamic CSS Classes with Vue

Vue is a pragmatic framework, it gets out of your way, at least that it how it feels for me. It encourages best practices, while not forcefully dictating a way top develop. In regards to styling, it allows us to assign CSS classes and even specific styles dynamically.

One thing I was missing though, is how to create CSS classes dynamically to begin with. It’s hard to find any hints on that, but the Vuetify folks have figured out a trick to do it.

Basically what we have to do is create a templated CSS string we fill with our dynamic values, then create a style element in the DOM and assign the string to its innerHTML. This evaluates the CSS code and brings our class(es) to life, which we can then use on any of our components.

Here is an example for a single file component:

export default {
  computed: {
    maxWidth() {
      const margin = 48;
      return this.$vuetify.breakpoint.width - margin;
    },
  },
  methods: {
    generateStyleDef() {
      return `
        .my-new-dynamic-class {
          max-width: ${this.maxWidth}px !important;
        }
      `;
    },
    applyStyle(styleDef) {
      let style = document.createElement('style');
      style.type = 'text/css';
      document.head.appendChild(style);
      style.innerHTML = styleDef;
    },
  },
  created() {
    let styleDef = this.generateStyleDef();
    this.applyStyle(styleDef);
  },
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s