我正在开发一种布局,其中父容器内的子元素必须始终保持 16:9 的宽高比。父容器的大小可以通过 JavaScript 动态调整,子容器也应该相应地调整其尺寸。 问题来了:
这是我的代码的最小可重现示例:
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
height: 90px;
width: 160px;
background-color: red;
display: flex;
justify-content: center;
/* tried to add: align-items: center; - it makes the child disappear. */
}
#child {
height: auto; /* tried also: max-height: 100%; */
max-width: 100%;
aspect-ratio: 16 / 9;
background-color: yellow;
object-fit: contain;
}
</style>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
<button onclick="increaseHeight()">increase height</button>
<button onclick="increaseWidth()">increase width</button>
<script>
var height = 90;
var width = 160;
function increaseHeight() {
height += 100;
document.getElementById('parent').style.height = height + 'px';
}
function increaseWidth() {
width += 100;
document.getElementById('parent').style.width = width + 'px';
}
</script>
</body>
</html>
如何确保子级始终保持 16:9 的宽高比,无论父级的尺寸如何,并且不会消失或损坏?任何帮助将不胜感激!
既然您正在使用
flex
,
您需要在
align-items
上设置 #prent
才能不是 stretch
(默认设置)。
并且
#child
应该在 auto
弹性基础上收缩和增长:
var height = 90;
var width = 160;
function increaseHeight() {
height += 100;
document.getElementById('parent').style.height = height + 'px';
}
function increaseWidth() {
width += 100;
document.getElementById('parent').style.width = width + 'px';
}
#parent {
height: 90px;
width: 160px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}
#child {
flex: 1 1 auto;
aspect-ratio: 16 / 9;
background-color: yellow;
object-fit: contain;
}
<div id="parent">
<div id="child"></div>
</div>
<button onclick="increaseHeight()">increase height</button>
<button onclick="increaseWidth()">increase width</button>