Don't Override Component CSS

It can be really tempting to quickly modify a component's CSS from outside of the component. If all you need is a slight modification, it seems harmless — but it's not.

Let's say you have a button that is normally blue, but in this specific case you need it to be green. You can override the background color from the parent component like this:

<Button class="green">Make this button green</Button>
.green.button {
background: green;

This does work, but it's very fragile and prone to breaking.

What if the classname changes?

What if the HTML of the component is modified?

Anyone making changes to the button component will have no idea that the background color is overridden in this component. They won't know to update this component too.

Instead, we can just extend the functionality of the button component. That way we keep all of the code that modifies the button inside of the button component.

Here, we can add a is-green prop to the button component:

<Button is-green>Make this button green</Button>
/* No extra styles needed! */

By adding to the component itself, we also make it easier for anyone else who might need this button to be green in the future!

I've created a demo showing the original component and the new one with the added prop.

Edit on CodeSandbox

Want to level up your Vue skills?

With over two million reads and 11,067 subscribers, you've come to the right place.

Subscribe now to get exclusive insights and tips every week.