How to override styles in style
OK, here is a concrete example showing how to override styles in Vue components.
Example: Overwrite component styles
Suppose we have a component, which contains some styles:
<template> <div class="my-component"> <h1>title</h1> <p>content</p> </div> </template> <style scoped> .my-component { background-color: blue; } h1 { color: white; } </style>
need
We want to override in the parent componenth1
style, making its color red.
Method 1: Use a higher priority selector
In the parent component, we can use a higher priority selector to override the style:
<template> <div> <MyComponent /> </div> </template> <style> .my-component h1 { color: red; /* Overwrite styles in subcomponents */ } </style>
Method 2: Use !important
If needed, you can use!important
Make styles more prioritized:
<template> <div> <MyComponent /> </div> </template> <style> h1 { color: red !important; /* Forced coverage */ } </style>
Method 3: Use the depth selector (scoped)
ifMyComponent
is a child component that we can use a depth selector to override the style:
<template> <div> <MyComponent /> </div> </template> <style scoped> ::v-deep h1 { color: red; /* Override with depth selector */ } </style>
Summarize
- Using a higher priority selector is the most common approach.
-
!important
It can be covered by force, but should be used with caution. - use
::v-deep
Subcomponent styles in scoped styles can be overridden.
You can choose the right method according to the specific situation! If there are any other questions, please let me know.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.