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:

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

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:

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

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