The principle of CSS implementing scoped

Article directory


foreword

CSS Scoped is a technique for styling locally and isolating scopes on a Web page. The key to implementing Scoped is to limit the style to its specified scope, so that the style is not affected by other elements on the page. In web applications, there are generally two ways to achieve Scoped effects: using a selector with a unique ID and using an attribute selector.


1. Use a selector with a unique ID

When using Vue, React, Angular and other front-end frameworks, we can use unique ID selectors to implement Scoped CSS. The principle of this method is that the framework will automatically generate the corresponding unique attribute according to the unique ID of the component, and add it to the root element of the component. For example:

<div id="app">
  <div class="example" data-v-1a161d4c>
    <h1>Title</h1>
    <p>Content</p>
  </div>
</div>

In the above example, data-v-1a161d4c is a unique property automatically generated by Vue that will be added in all CSS style rules used in the component. In this way, the attribute selector can be used when applying CSS style rules to ensure that the style only takes effect for the elements within the component. For example:

.example[data-v-1a161d4c] h1 {
  font-size: 20px;
}

In the above example, [data-v-1a161d4c] it is an attribute selector, which is used to filter elements with corresponding unique attribute values, thereby limiting the scope of CSS style rules and achieving the effect of Scoped CSS.

2. Use attribute selectors

1. Another way to implement Scoped CSS is to use attribute selectors. This approach works by using selectors with specific attributes to ensure that style rules apply only to specific elements on the page. For example:

<div class="example" data-scoped>
  <h1>Title</h1>
  <p>Content</p>
</div>

2. In the above example, we have used  data-scoped a specific attribute named as and added it  example on the element. When applying this attribute selector, we can use the following CSS rules:

.example[data-scoped] h1 {
  font-size: 20px;
}

In this case, the style rule is only applied to the element with this attribute, thus avoiding the situation of applying the style rule on the whole page, so the effect of Scoped CSS can also be achieved. It should be noted that since attribute selectors may affect the performance of CSS, we should use this implementation with caution.


Summarize

To sum up, the principle of implementing Scoped is to limit the scope of style rules to avoid them being affected by other elements on the page. Whether you use unique ID selectors or attribute selectors, they can prevent CSS style rules from leaking into other components or the entire page, thereby achieving Scoped effects.

Guess you like

Origin blog.csdn.net/weixin_54079103/article/details/131010995