You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于CSS构建行列数可变的固定尺寸Vue表格

固定尺寸正方形表格解决方案

修改后的HTML代码

<section class="arena-preview">
    <table :style="{'--size': size}">
        <tr v-for="row in size">
            <td v-for="column in size"></td>
        </tr>
    </table>
</section>

修改后的CSS代码

@media only screen and (min-width: 768px) {
    .arena-preview {
      flex: 3;
      max-width: 60%;
      overflow-x: auto;
      aspect-ratio: 1;
    }
}

.arena-preview {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 100%;
    box-sizing: border-box;
    aspect-ratio: 1;
    max-width: 400px;
    max-height: 400px;
    margin: 0 auto;
}

table {
    width: 100%;
    height: 100%;
    table-layout: fixed;
    border-collapse: collapse;
    box-sizing: border-box;
}

table, td {
    border: 1px solid;
}

tr {
    height: calc(100% / var(--size));
}

td {
    width: calc(100% / var(--size));
    aspect-ratio: 1;
    padding: 0;
    box-sizing: border-box;
}

关键调整说明

  • 容器强制正方形:给.arena-preview添加aspect-ratio: 1,确保容器始终是正方形,同时设置max-width/max-height限制最大尺寸,避免在大屏上过度放大。用align-items: center替换原有的align-content,保证表格在容器内垂直居中。
  • 表格填充容器:将表格的width改为100%并新增height: 100%,让表格完全占满容器空间。table-layout: fixed强制浏览器均分列宽,不会因内容或行列数变化改变布局。
  • 行列空间均分:通过Vue的:style把size变量传递为CSS自定义属性--size,再用calc(100% / var(--size))计算每行每列的尺寸,确保2到10行列时,每个单元格都能均匀分配容器空间。
  • 单元格强制正方形:使用aspect-ratio: 1直接锁定单元格宽高比为1:1,这是最可靠的正方形实现方式,配合box-sizing: border-box让边框、内边距不会破坏比例。如果需要内边距,保留box-sizing即可,无需额外调整尺寸计算。
  • 移除干扰性padding:原代码的padding: 15px会让单元格尺寸超出预期,先移除保证布局准确,之后可根据需求重新添加,box-sizing会自动将内边距纳入尺寸计算。

内容的提问来源于stack exchange,提问作者Uli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 13:55:10