繁体   English   中英

当孩子们这样做时,我如何让父 div 调整大小?

[英]How do I get a parent div to resize when the children do?

我正在处理的程序遇到了这个问题,但我无法找到解决方案。 基本上我有一个网络应用程序,在初始渲染时整个页面的高度为 X。有一种背景颜色,并且该颜色覆盖了页面的整个高度。

初始渲染后的片刻,数据被异步获取并添加到页面中。 数据导致页面的总高度变大。 不幸的是,只有页面的原始高度显示背景颜色,低于该高度背景变为白色。

在进一步调查中,我发现这是由于父 div 在子 div 调整大小时没有调整。 基本上,通过异步数据加载向其添加元素的 div 的高度会增加,但围绕它的父元素(以及具有背景颜色的元素)不会。

在我的调查中,我找到了一个部分解决方案:将“高度”设置为“自动”。 这个解决方案的问题是当页面最初加载时,背景颜色只应用到页面的实际内容部分,而不是填充屏幕。 因此,如果我将高度设置为“自动”,则在添加项目后自行更正之前首次加载页面时颜色会搞砸,如果高度为“100%”,则在添加项目后颜色会搞砸.

我整理了一个重现问题的准系统 HTML 文件:

<!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>

你可以设置min-height: 100vh;<\/code> #root<\/code>元素 CSS 上,使其始终至少是视口的高度。

"

在#root 上设置 100% 的最小高度,而不是高度,似乎可以解决问题:

<!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            min-height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>

你可以使用height: fit-content; width: fit-content; 在父元素上

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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