【问题标题】:have CSS, including position: absolute; contained to a container node [duplicate]有 CSS,包括 position: absolute;包含在容器节点中[重复]
【发布时间】:2021-12-30 20:22:09
【问题描述】:

如何将 CSS,包括 position: absolute; 包含到容器节点中?即带有position: absolute 的元素应该位于容器节点的左上角,而不是整个文档的左上角。 类似于iframe

使用 shadow DOM 隔离 styleNode 中的 CSS 的示例代码,我无法控制:

test.html

<html>
<body>
<div>this should still be visible and not affected by container styling</div>

<div id="container"></div>


<script>
    let container = document.querySelector('#container')
    const shadow = container.attachShadow({mode: 'open'}); 
    const styleNode = document.createElement('style');
    styleNode.textContent = `
    div {
        background: blue;
        font-size: 32px;
        position: absolute;
        top: 0;
        left: 0;
    }
    `;

    shadow.appendChild(styleNode);
    const contentNode = document.createElement('div');
    contentNode.textContent = `Hello World`;
    shadow.appendChild(contentNode);
</script>
</body>
</html>

期望的结果: 'Hello World' 显示在 'this 应该仍然可见' 下,而不是在它之上。

【问题讨论】:

    标签: css shadow-dom


    【解决方案1】:

    绝对定位是相对于第一个向上的祖先发生的,它本身有一个位置集。

    如果找不到这样的显式定位,则默认使用 body 元素。

    如果你给父元素位置相对定位将发生相对于那个。

    <html>
    <body>
    <div>this should still be visible and not affected by container styling</div>
    
    <div id="container"></div>
    
    
    <script>
        let container = document.querySelector('#container')
        const shadow = container.attachShadow({mode: 'open'}); 
        const styleNode = document.createElement('style');
        styleNode.textContent = `
        div {
            background: blue;
            font-size: 32px;
            position: absolute;
            top: 0;
            left: 0;
        }
        `;
    
        shadow.appendChild(styleNode);
        const contentNode = document.createElement('div');
        contentNode.textContent = `Hello World`;
        shadow.appendChild(contentNode);
    </script>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-21
      • 2023-01-25
      • 2013-01-23
      • 2012-11-03
      • 2015-04-15
      • 2022-12-23
      • 2019-03-17
      • 1970-01-01
      相关资源
      最近更新 更多