Override scoped css

tip#22

Changing the style of a scoped vue componente can be trick if you don't understand how CSS specificity works. Take those three buttons for instance. They have a default grey look, but I want to override the color, creating a success and danger style.

btn.vue default grey look

The first attempt is to simply create a .danger and .success class with the changes, but that doesn't work as expected:

<style lang="css">
.success {
border-color: #3AC162;
background-color: #5FCF80;
}
  .danger {
background-color: #ED5A5A;
border-color: #EA4343;
}
</style>

Inspecting the element you see that the colors where override by the selector:
.btn[data-v-51167f5d] which has higher specificity over .success as you can check with this awesome tool: https://specificity.keegan.st/


The only way to override the css is to get higher points of specificity. For example, adding the class .btn to the selector gets the same two points but it still looses because of the order of precedence.

<style lang="css">
.btn.success {
border-color: #3AC162;
background-color: #5FCF80;
}
  .btn.danger {
background-color: #ED5A5A;
border-color: #EA4343;
}
</style>

So, if we add another selector like .parent, we increase the specificity to 3, which is enough to override the scoped css.

<style lang="css">
.parent .btn.success {
border-color: #3AC162;
background-color: #5FCF80;
}
  .parent .btn.danger {
background-color: #ED5A5A;
border-color: #EA4343;
}
</style>

Another solution is to add the scoped to the parent component:

<style lang="css" scoped>
.btn.success {
border-color: #3AC162;
background-color: #5FCF80;
}
  .btn.danger {
background-color: #ED5A5A;
border-color: #EA4343;
}
</style>