如何实现v-card宽度随高度自适应 保持16:9固定宽高比
动态排布v-card固定16:9宽高比(宽度随高度自适应)实现方案
方案核心
不需要用JS做复杂的宽高换算,直接用CSS原生aspect-ratio属性即可实现需求:卡片高度跟随行高自适应,宽度自动按16:9比例计算,不会出现拉伸变形。
修改要点
- 移除v-card上原有硬编码的
:width、:height绑定,避免手动计算的尺寸互相冲突 - 给v-card设置
height: 90%(撑满当前行可用高度,预留少量边距避免卡片贴边) - 给v-card增加
aspect-ratio: 16/9属性,强制卡片保持16:9宽高比,宽度会自动根据高度计算生成 - 给v-row、v-col增加少量内边距,避免卡片之间拥挤
调整后核心代码
模板代码
<template> <v-app > <v-main> <v-row v-for="i in numberOfRow" :key="i" align="center" justify="space-around" :style="`height: ${100/numberOfRow}%;`" class="pa-3" > <v-col v-for="n in numberOfCol(i)" :key="n" style="display:flex; justify-content: center;align-content: center;" class="py-3" > <v-card elevation="10" style=" display: flex; flex-direction: row; justify-content: center; height: 90%; aspect-ratio: 16/9; " > <v-img src="https://i.redd.it/c3uhsgo1vx541.jpg" width="20%" height="100%" style="border-radius: 0 100% 100% 0%;" /> <div style="width: 70%; height: 100%;"> <div style="width: 100%; height: 50%; display: flex;text-align: center; align-items: flex-end;"> <v-card-text class="text-h2 primary--text">Title</v-card-text> </div> <div style="width: 100%; height: 20%; text-align: center;"> <v-card-text class="text-body-2">This is the subtitle</v-card-text> </div> </div> </v-card> </v-col> </v-row> </v-main> <v-footer color="#005686" app bottom fixed padless> <span class="white--text"></span> </v-footer> </v-app> </template>
脚本代码
原有行列计算逻辑无需修改,可直接保留:
export default { name: "App", components: { }, data() { return { numberOfSection: 2 }; }, computed: { numberOfRow() { if(this.numberOfSection%2 === 0) { return 2; }else if(this.numberOfSection%3 === 2) { return Math.floor(this.numberOfSection / 3) + 1; }else { return Math.floor(this.numberOfSection / 3) + this.numberOfSection%3; } } }, methods: { numberOfCol( rowNumber) { if( this.numberOfSection%2 === 0) { return this.numberOfSection/2; }else{ return rowNumber === Math.floor(this.numberOfSection / 3) + 1 ? this.numberOfSection%3 : 3; } } } }
旧浏览器兼容方案
aspect-ratio支持Chrome 88+、Firefox 89+、Safari 15.4+的所有现代浏览器,如果需要兼容更早版本,可以用CSS padding比例hack实现同等效果:
- 给v-card外层套一层容器div,设置
position: relative; height: 90%; - 给容器设置
width: calc(当前行高 * 16 / 9),行高可以直接用你已有的90 / numberOfRow + 'vh'计算值 - 给内部v-card设置
position: absolute; width: 100%; height: 100%; inset: 0;即可
当前效果参考

调整完成后,无论卡片数量怎么变化、行列数怎么计算,所有v-card都会严格保持16:9比例,宽度自动跟随高度适配,不会出现拉伸、比例失调的问题。
内容的提问来源于stack exchange,提问作者Zarcoin
相关产品推荐
相关产品推荐

