Categories
JavaScript Vue

Adding Scoped Styles in Vue Components

Spread the love

To add component styles that are only applied to the component, we have to scope it to the component.

To do that, we have to add the scoped keyword to the style tag.

Scoped styles are only available to single-file components.

All we have to do is write:

<style scoped>
/* local styles */
</style>

in our component.

Then all the styles inside it will only apply to the current component.

We can mix both global and local styles in the same component.

We just have to write:

<style>
/* global styles */
</style>

<style scoped>
/* local styles */
</style>

Then the styles in the first style tag is applied globally, and the styles in the other one are applied locally.

We can also add selectors to apply styles that affect the current and child components.

For instance, we can write:

<style scoped>
.a >>> .b { /* ... */ }
</style>

Then the styles will be applied to anything with class b if it’s inside the n element with class a in the current component.

DOM content generated with v-html isn’t affected by scoped styles, but we can still style them with deep selectors.

Scoped styles don’t eliminate the need for classes. This is because classes are the faster way to style elements.

We can use the scoped attribute on a style tag to make them styles inside applied locally.

Also, we can have deep selectors to apply styles to a child component of the current component.

DOM content rendered with v-html aren’t affected by scoped styles, but we can style them with deep selectors.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.