When a `<style>` tag has the `scoped` attribute, its CSS will apply to elements of the current component only. This is similar to the style encapsulation found in Shadow DOM. It comes with some caveats, but doesn't require any polyfills. It is achieved by using PostCSS to transform the following:
@@ -14,7 +14,7 @@ When a `<style>` tag has the `scoped` attribute, its CSS will apply to elements
</template>
```
Into the following:
转换结果:
``` html
<style>
...
...
@@ -28,27 +28,27 @@ Into the following:
</template>
```
## Mixing Local and Global Styles
## 混用本地和全局样式
You can include both scoped and non-scoped styles in the same component:
你可以在一个组件中同时使用有作用域和无作用域的样式:
``` html
<style>
/* global styles */
/* 全局样式 */
</style>
<style scoped>
/* local styles */
/* 本地样式 */
</style>
```
## Child Component Root Elements
## 子组件的根元素
With `scoped`, the parent component's styles will not leak into child components. However, a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. This is by design so that the parent can style the child root element for layout purposes.
@@ -56,20 +56,20 @@ If you want a selector in `scoped` styles to be "deep", i.e. affecting child com
</style>
```
The above will be compiled into:
上述代码将会编译成:
``` css
.a[data-v-f3f3eg9].b{/* ... */}
```
Some pre-processors, such as Sass, may not be able to parse `>>>` properly. In those cases you can use the `/deep/` combinator instead - it's an alias for `>>>` and works exactly the same.
DOM content created with `v-html` are not affected by scoped styles, but you can still style them using deep selectors.
通过 `v-html` 创建的 DOM 内容不受作用域内的样式影响,但是你仍然可以通过深度作用选择器来为他们设置样式。
## Also Keep in Mind
## 还有一些要留意
-**Scoped styles do not eliminate the need for classes**. Due to the way browsers render various CSS selectors, `p { color: red }` will be many times slower when scoped (i.e. when combined with an attribute selector). If you use classes or ids instead, such as in `.example { color: red }`, then you virtually eliminate that performance hit. [Here's a playground](https://stevesouders.com/efws/css-selectors/csscreate.php) where you can test the differences yourself.
-**CSS 作用域不能代替 class**。考虑到浏览器渲染各种 CSS 选择器的方式,当 `p { color: red }` 设置了作用域时 (即与特性选择器组合使用时) 会慢很多倍。如果你使用 class 或者 id 取而代之,比如 `.example { color: red }`,性能影响就会消除。你可以在[这块试验田](https://stevesouders.com/efws/css-selectors/csscreate.php)中测试它们的不同。
-**Be careful with descendant selectors in recursive components!** For a CSS rule with the selector `.a .b`, if the element that matches `.a` contains a recursive child component, then all `.b` in that child component will be matched by the rule.