[英]Cannot get child DIV % height to work because of parent margin auto
我正在现有的框架内工作,因此只能编辑CSS / HTML。 我在父母中有两个孩子DIV,我希望分别是父母身高的80%和20%。 但是,由于父母有'margin:auto;', 我无法上班。
有人可以帮忙吗? 我知道我可以使用JS来解决此问题,但强烈希望不要这样做。 如果可能,希望使用CSS修复程序。
请注意,由于我在第三方产品框架内工作,因此无法更改标记区域以外的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>
如果您的父母有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>
您的身高百分比不起作用,因为您的父母没有身高:)
只需增加height: 100%;
到.template-contents
,它将起作用:
.template-container { display: flex; width: 100%; padding: 10px; text-align: center; height: 100%; box-sizing: border-box; list-style: none; line-height: 1.42857; } .template-contents { display: block; margin: auto; text-align: center; width: 100%; height: 100%; box-sizing: border-box; } .flexer { width: 200px; height: 200px; border: 1px solid; } .ztop { height: 80%; } .zbottom { height: 20%; }
<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> </html>
在父元素中使用高度100%。
.template-contents {
display: block;
margin: auto;
text-align: center;
width: 100%;
height: 100%;
box-sizing: border-box;
}
或将边距更改为0自动
.template-contents {
display: block;
margin: 0 auto;
text-align: center;
width: 100%;
box-sizing: border-box;
}
即使您无法更改HTML,也可以始终覆盖CSS。 所以只要添加这个
.template-contents {
margin: 0 auto;
}
这样可以使水平边距保持自动状态,但删除垂直边距。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.