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