简体   繁体   中英

rem in web component shadow dom

We know that we can set font-size on html as the rem base in normal DOM nodes, and I use this trick to make my font of my app more flexible, dynamically changed with js.

However, when I created a web component, I found rem inside the shadow DOM always refers to 16px, even though I tried adding a style *{ font-size:72px } inside the shadow DOM. 16px is the common browser default font size.

Here's a simple demo: https://jsfiddle.net/qmacwb6r/

<html>
<head>
<script>
var template =`
<style>
* {
    font-size: 72px;
}
div {
    font-size:2rem;
}
</style>
<div>
    I am 2rem = 2*broser default
</div>
`
class TestTemplate extends HTMLElement {
    constructor(){
        super();
        this.rt = this.attachShadow({mode:"open"});
        this.rt.innerHTML = template;
    }
}
customElements.define("test-component", TestTemplate);
</script>
</head>
<body>
<test-component></test-component>
</body>
</html>

I also tried calling getRootNode() in the console.

For normal DOM nodes, it returns HTMLElement, whereas for shadow DOM nodes, it returns ShadowRoot, which, unlike HTMLElement, cannot be styled.

Is it possible to make the rem base font of the nodes in shadow DOM variable and controllable?

Unless I am missing something rem values are always based on the font-size set for the <html> tag like this:

html {
  font-size: 100px;
}

With the above the size 1rem is equal to 100px .

Here is an example where I set the font-size for html to 4px. And then use rem values in the component.

 var template = ` <style> :host, :root { font-size: 48px; } .rem2 { font-size:2rem; } .rem3 { font-size:3rem; } </style> <p>I am 48px Times</p> <div class="rem2">I am 2rem = 2*browser default</div> <div class="rem3">I am 3rem = 3*browser default</div> `; class TestTemplate extends HTMLElement { constructor(){ super(); this.rt = this.attachShadow({mode:"open"}); this.rt.innerHTML = template; } } customElements.define("test-component", TestTemplate); 
 html { font: 4px Courier; } body { font: 24px Tahoma; } 
 <div>Before</div> <test-component></test-component> <div>After</div> 

Run this and then go look in the DevTools computed tab. You will see that: 1. the font-size for the text I am 2rem = 2*browser default is only 8px 2. the font-size for the text I am 3rem = 3*browser default is 12px;

The font-size for body and :host do not have any affect on the rem sizes. Only the font-size in the <html> tag does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM