如何将自定义样式仅应用于特定元素?
问题描述:
我正在开发一个主题型聚合物网络组件。由于每custom-style文档,我做了以下内容:如何将自定义样式仅应用于特定元素?
<link rel="import" href="themes/my-element-theme.html">
<style is="custom-style" include="my-element-theme"></style>
然而,这是一把钝刀,因为它适用的自定义主题,以我的所有元素。
一个解决方案是我的范围内的所有主题样式的CSS类,如下所示:
:root custom-element.my-element-theme {
font-family: 'Noto Sans', 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif;
}
然而,这使得它难以自定义样式应用到整个文档。
有没有办法将自定义样式更有选择性地应用到元素,比如使用CSS选择器?什么是最佳做法?
答
您绝对可以使用选择器来选择性地将样式应用到您的可移动主题元素。
最好使用自定义属性和mixins并将其值设置为目标元素。这里有一个例子:
<!DOCTYPE html>
<html>
<head>
<link href="http://polygit.org/components/polymer/polymer.html" rel="import" />
<style is="custom-style">
.container1 my-elem {
--my-elem-span: {
color: red;
}
}
.container2 my-elem {
--my-elem-span: {
color: blue;
}
}
</style>
</head>
<body>
<div class="container1">
<my-elem>hello red</my-elem>
</div>
<div class="container2">
<my-elem>hello blue</my-elem>
</div>
<dom-module id="my-elem">
<template>
<style>
:host { display: block; }
:host span {
@apply(--my-elem-span);
}
</style>
<span><content></content></span>
</template>
<script>
Polymer({
is: 'my-elem'
});
</script>
</dom-module>
</body>
</html>
而且像你这样通过将CSS规则在一个单独的样式模块可以外部化你的风格。
<dom-module id="my-elem-theme">
<template>
<style>
.container1 my-elem {
--my-elem-span: {
color: red;
}
}
.container2 my-elem {
--my-elem-span: {
color: blue;
}
}
</style>
</template>
</dom-module>
然后导入你的方式:
<link rel="import" href="my-elem-theme.html">
<style is="custom-style" include="my-elem-theme"></style>