首页 > 解决方案 > 由于父边距自动,无法使子 DIV % 高度工作

问题描述

我在现有框架内工作,因此我可以编辑的 CSS / HTML 受到限制。我在父母中有两个孩子 DIV,我想成为父母身高的 80% 和 20%。但是,由于父级具有 'margin: auto;' 我无法获得工作的高度。

有人可以帮忙吗?我知道我可以使用 JS 来解决这个问题,但我强烈倾向于不这样做。如果可能的话,更喜欢 CSS 修复。

请注意,因为我在第 3 方产品框架中工作,所以我无法更改标记区域之外的 HTML 或 CSS。

有关问题的示例,请参见 jsFiddle:https ://jsfiddle.net/6vb5910m/

谢谢

<html>
<body>
    <div class="flexer">
        <div class="template-container">
            <div class="template-contents">
            <!-- Cannot change anything above this line -->

                    <div class="ztop" style="background: rgb(200,0,0,0.3);">
                        I am 80% of Parent Height
                    </div>
                    <div class="zbottom"  style="background: rgb(0,200,0,0.3);">
                        I am 20% of Parent Height
                    </div>

            <!-- Cannot change anything below this line -->
            </div>
        </div>
    </div>
</body>

标签: htmlcss

解决方案


如果你父母有auto身高,恐怕这是不可能的。

父级将始终扩展到包含所有子级,因此其高度取决于子级的高度。

如果你的孩子也依赖于父母的身高,那么你就有了一个无限循环。

我认为唯一的解决方案是使用一些 Javascript,您可以使用它动态获取父级高度并将正确的高度应用于子级。

或者,如果您不需要auto此页面上的高度,您可以直接在源代码中覆盖template-contents' 高度,使其不适用于其他页面?

<html>
    <body>
        <div class="flexer">
            <div class="template-container">
                <div class="template-contents">
                <!-- Cannot change anything above this line -->

                    <style>
                        .template-contents {
                            height: 100%;
                        }
                    </style>

                    <div class="ztop" style="background: rgb(200,0,0,0.3);">
                        I am 80% of Parent Height
                    </div>
                    <div class="zbottom"  style="background: rgb(0,200,0,0.3);">
                        I am 20% of Parent Height
                    </div>

                <!-- Cannot change anything below this line -->
                </div>
            </div>
        </div>
    </body>
</html>

推荐阅读