【问题标题】:Change shadow dom rem size更改 shadow dom rem 大小
【发布时间】:2021-05-14 18:20:59
【问题描述】:

我正在使用影子 DOM 进行 CSS 隔离。我希望 rem 字体大小使用影子 DOM 中的 HTML 元素字体大小。

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

这是一个小代码 sn-p 演示我想要做什么。

<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>

【问题讨论】:

  • 所以从.shadow-div 中删除font-size,或者将其显式设置为inherit ...?

标签: javascript html css shadow-dom


【解决方案1】:

shadowRoots 不是文档,所以不要有&lt;html&gt;&lt;head&gt;&lt;body&gt; 标记;
shadowRoots 更像是 DocumentFragments

您根据:host 选择器设置阴影内容的样式;并且由于 shadow DOM 是封装的,因此类针对该 DIV 的需求较少

REM 始终基于html 定义;在组件中使用 em 代替

还要注意 inheritable 属性,例如 color '涓滴' 到组件中和 do 在 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: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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 2014-08-27
    • 2014-09-17
    • 2019-06-03
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多