正如另一个答案中提到的,要对影子 DOM 的主机进行样式设置,请使用@host
选择器。在自定义元素的情况下,自定义元素的宿主就是它自己。
下面是一个示例,说明如何从自定义元素的<style>
标签中设置宿主元素或自定义元素本身的样式。
<!DOCTYPE html>
<html>
<head>
<title>index</title>
<script src="packages/polymer/boot.js"></script>
</head>
<body>
<polymer-element name="my-element">
<template>
<style>
@host {
my-element {
display: block;
border: 1px solid black;
}
}
p {
color: red;
}
#message {
color: pink;
}
.important {
color: green;
}
</style>
<p>Inside element, should be red</p>
<div id="message">
The message should be pink
</div>
<div class="important">
Important is green
</div>
<div>
<content></content>
</div>
</template>
<script type="application/dart" src="index.dart"></script>
</polymer-element>
<p>outside of element, should be black</p>
<div id="message">
The outside message should be black
</div>
<div class="important">
Outside important is black
</div>
<my-element>Hello from content</my-element>
<!-- If the script is just an empty main, it's OK to include inline. -->
<!-- Otherwise, put the app into a separate .dart file. -->
<script type="application/dart">main() {}</script>
</body>
</html>
注意@host
样式中的块:
@host {
my-element {
display: block;
border: 1px solid black;
}
}
因为这个特定的自定义元素不扩展任何元素,所以它不默认为块。
这是样式化后的样子: