【发布时间】:2021-11-26 05:20:48
【问题描述】:
我希望有一个 div 部分,在保持比例的同时尽可能地填充其 div 父级。
渲染结果是这样的:
到目前为止我所拥有的:
html,
body {
height: 100%;
}
.parent {
/* Parent's height and width are unknown,
it could be dynamic, e.g. parent is part of a flex layout. */
height: 80%;
width: 90%;
border-style: solid;
border-width: 2px;
border-color: black;
}
.child {
width: 90vw;
/* 90% of viewport vidth */
height: 50.625vw;
/* ratio = 9/16 * 90 = 50.625 */
max-height: 90vh;
max-width: 160vh;
/* 16/9 * 90 = 160 */
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: #A0522D;
}
<div class="parent">
<div class="child">
content that is not images...
</div>
</div>
这个 css 的行为就像我想要的那样,但是这是使用视口而不是父 div,这在实际条件下是一个问题。
我正在寻找一种基于父div的填充方式。
【问题讨论】:
-
不要使用 90vw,而是使用 90% 或您需要的任何百分比 (%)。请注意,50.625% 也有效。
-
使用 90% 和 50.625% 使子 div 只跟随父级而不保持其比例。
-
尝试更改“child”
position: relative;并移除顶部、底部、左侧和右侧的位置。使用边距,您可能也想删除它,除非您需要水平居中,然后使用margin 0 auto;我现在有一些测试代码,父 div 为 40%,子 div 为 80%,它可以工作,我有尝试了几种不同的百分比。除了这些变化之外,没有其他区别。 -
我无法提出您的建议;子 div 跟随父的宽度,所以我确实打破了我想要的子比例约束。
标签: css