[英]Change shadow dom rem size
I am using a shadow DOM for CSS isolation.我正在使用影子 DOM 进行 CSS 隔离。 I want the
rem
font size to use the HTML element font size in the shadow DOM.我希望
rem
字体大小在阴影 DOM 中使用 HTML 元素字体大小。
The font in <div class="shadow-div">shadow DOM font (should be 100px)</div>
should be 100px
but the rem size is still 16px
. <div class="shadow-div">shadow DOM font (should be 100px)</div>
中的字体应该是100px
但 rem 大小仍然是16px
。
Here is a small code snippet demonstrating what I want to do.这是一个小代码片段,演示了我想要做什么。
<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>
shadowRoots are not Documents , so don't have <html><head><body>
markup; shadowRoots不是 Documents ,所以没有
<html><head><body>
标记;
shadowRoots are more like DocumentFragments shadowRoots更像DocumentFragments
You style shadow content based from the :host
selector;您可以根据
:host
选择器设置阴影内容的样式; and since shadow DOM is encapsulated, there is less need for classes to target that one DIV并且由于 shadow DOM 是封装的,因此类针对该 DIV 的需求较少
REMs are always based on the html
definition; REM 始终基于
html
定义; use em instead inside the Component在组件内使用em
Also note how inheritable properties, like color
'trickle down' into Components and do style content inside shadowDOM ( font-size
also, but you overload it in the Component in this code)还要注意可继承的属性,比如
color
“涓涓细流”到组件中,以及在 shadowDOM 中做样式内容( font-size
也是如此,但是你在这段代码的组件中重载了它)
see: https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/请参阅: https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/
That simplifies your code to:这将您的代码简化为:
<style> html { font-size: 10px } body { font-size: 3rem; color:red } </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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.