The style tag in a Vue component with the scoped attribute indicates that the CSS style in the style applies only to the current component element. In this article, I will share an example of the style attribute scoped in the VUE component

Scoped CSS

The Scoped CSS specification is a CSS specification that Web components produce without contaminating or being contaminated by other components.

The style tag in the Vue component is scoped to indicate that the CSS style in the style applies only to the current component element. This is done by using PostCSS to change the following:

<style scoped>
.example {
 color: red;
}
</style>
 
<template>
 <div class="example">hi</div>
</template>
Copy the code

Render result:

<style>
.example[data-v-f3f3eg9] {
 color: red;
}
</style>
 
<template>
 <div class="example" data-v-f3f3eg9>hi</div>
</template>
Copy the code

Mix global and local properties

<style>
/* global styles */
</style>
 
<style scoped>
/* local styles */
</style>
Copy the code

About the root element of the child component

  • When scoped is used, the parent component’s style style will not permeate the child component, while the child component’s root node element will be influenced by both the parent CSS style and the child CSS style scoped. This is designed so that the parent component can layout the child component’s root element.

  • Styles in the.vue template are loaded on demand, and styles in that component are appended to the head tag when visiting a page. If both parent and child components control the root element of a child component, styles in the parent component are overwritten later.

The deep selector can use ‘>>>’ or ‘deep’ to control elements in a child component scoped.

<template>
 <div id="app">
  <gHeader></gHeader>
 </div>
</template>
 
<style lang="css"Scoped >.gheader /deep/.name{scoped :red; }.gheader >>>.name{// <div style> <div style = "box-sizing: border-box! Important; word-wrap: break-word! Important"gHeader">
 <div class="name"></div>
</div>
Copy the code

Some preprocessors such as Sass cannot parse >>> properties. In this case, you can use deep, which is an alias for >>> and works in the same way. Dynamically generated content is dynamically created using V-HTML DOM content. This is not influenced by scoped, but you can still use the deep selector to control the content. Here’s a sidebar for rich text loaded using V-HTML in VUE. Rich text contains images, which may overflow on mobile phones

<div v-html="htmlContent" class="rich"></div> 
<style scope>
.rich>>> img{ display:block; max-width: 100%}
</style>
Copy the code

Note: the >>> here needs to use CSS syntax, writing in less will error

conclusion

Thank you for watching, if there are shortcomings, welcome to criticize.