实现说明
aspect-ratio 把盒子钉在固定宽高比上,高度随宽度走,无需 padding hack。
object-fit 决定媒体如何填充盒子,同时保持自身宽高比。
常见问题
这段样式作用于哪些元素?
规则命中 .video-container——按源码顺序生效,同优先级时后写的赢。
代码示例
.video-container {
aspect-ratio: 16 / 9;
width: 100%;
background: #000;
}
.video-container video {
width: 100%;
height: 100%;
object-fit: cover;
}
.square-avatar {
aspect-ratio: 1;
width: 80px;
border-radius: 50%;
overflow: hidden;
}
.poster {
aspect-ratio: 2 / 3;
max-width: 300px;
}