SoFunction
Updated on 2025-04-06

How to override styles in style in vue

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 componenth1style, 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!importantMake styles more prioritized:

<template>
  <div>
    <MyComponent />
  </div>
</template>

<style>
h1 {
  color: red !important; /* Forced coverage */
}
</style>

Method 3: Use the depth selector (scoped)

ifMyComponentis 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.
  • !importantIt can be covered by force, but should be used with caution.
  • use::v-deepSubcomponent 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.