“This is my 8th day of the November Gwen Challenge.The final text challenge in 2021”

Why is style penetration needed?

In the Vue project, when we introduced third-party component libraries (such as using element-UI), we needed to modify the third-party component library styles in local components without removing the scoped attribute and causing style overwriting between components. At this point we need style penetration to achieve the desired effect.

Why use itscoped?

“In a Vue component, adding the scoped attribute to the style tag to indicate that its style applies to the current module is a nice way to privatize styles.”

//button.vue
<template>
    <div class="button-warp">
        <button class="button">text</button>
    </div>
</template>.<style scoped>
    .button-warp{
        display:inline-block;
    }
    .button{
        padding: 5px 10px;
        font-size: 12px;
        border-radus: 2px;
    }
</style>
Copy the code

The HTML and CSS rendered by the browser are:

<div data-v-2311c06a class="button-warp">
  <button data-v-2311c06a class="button">text</button>
</div>
.button-warp[data-v-2311c06a]{
  display:inline-block;
}
.button[data-v-2311c06a]{
  padding: 5px 10px;
  font-size: 12px;
  border-radus: 2px;
}
Copy the code

Add a non-repeating data attribute to the HTML DOM node (such as: data-V-2311C06A) to indicate his uniqueness; At the end of each CSS selector (the compiled, generated CSS statement), add a data property selector for the current component (such as [data-V-2311c06a]) to privatise the style

How many ways are there to implement style penetration?

From the scoped principle above, we can see that a simple and crude way is to remove scoped

Implement style penetration in scoped case:

  1. >>>Only applies tocss
<style scoped> Outer >>> third party component {style \} </style>Copy the code
  1. ::v-deepOnly applies tosass
<style lang=" SCSS "scoped>Copy the code
  1. /deep/Only applies toless
<style lang="less" scoped> External /deep/ scoped components {style \} </style>Copy the code

Specific code examples are as follows:

<style lang=" SCSS "scoped>.outer ::v-deep .inner{
    padding:0 10px; </style> <style lang="less" scoped>.outer /deep/ .inner{
    padding:0 10px; } </style>.outer {
    width: 90px;
    margin-top: 15px;
    >>> .inner {
      text-align: center! important;
    }
}
</style>
Copy the code