改变阴影dom的大小



我使用阴影DOM来隔离CSS。我希望rem的字体大小使用阴影DOM中的HTML元素字体大小。

<div class="shadow-div">shadow DOM font (should be 100px)</div>中的字体应为100px,但rem大小仍为16px

下面是一小段代码片段,演示了我要做的事情。

<style>
html {
font-size: 16px;
}
</style>
<div>light dom font</div>
<div id="root"></div>
<script>
const root = document.getElementById('root');
root.attachShadow({ mode: 'open' });
const html = document.createElement('html')
html.innerHTML = `
<head>
<style>
html {
font-size: 100px;
}
.shadow-div {
font-size: 1rem;
}
</style>
</head>

<body>
<div class="shadow-div">shadow dom font (should be 100px)</div>
</body>
`;
root.shadowRoot.appendChild(html);
</script>

shadowRootsnot Documents,所以不要有<html><head><body>标记;
shadowRoots更像 DocumentFragments

根据:host选择器为阴影内容设置样式;并且由于影子DOM是封装的,所以类不需要针对一个DIV

REMs总是基于html定义;使用em而是在Component

中还要注意如何继承属性,如color"涓滴"到组件和样式内容在shadowDOM (font-size也,但你重载它在组件在这个代码)
见:https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/

将代码简化为:

<style>
html { font-size: 10px }
body { font-size: 3rem; color:green }
</style>
<div>3rem body font-size = 3 * html font-size</div>
<div id="root"></div>
<script>
document.getElementById('root')
.attachShadow({ mode: 'open' })
.innerHTML = `<style>
:host { font-size: 50px }
div   { font-size: 2rem }
p     { font-size: .5em }
</style>
50px Component font-size
<div>2rem = 2 * html font-size = 20px</div>
<p>.5em = .5 * :host font-size = 25px</p>`;
</script>

最新更新