Blazor中魔方2D表格四周按钮与中间行对齐布局求助
解决Blazor魔方表格与方向按钮的居中对齐问题
可以用CSS Grid布局来实现这个需求,它比表格嵌套更灵活,能轻松让四个方向的按钮和魔方表格的中间行对齐。以下是完整的实现代码:
步骤1:修改Blazor组件结构与逻辑
替换原有的表格代码,加入Grid容器和方向按钮,同时添加切换魔方面的逻辑:
<div class="cube-container"> <!-- 上方按钮(北) --> <button class="direction-btn north-btn" @onclick="() => SwitchFace('up')">see up</button> <!-- 左侧按钮(西) --> <button class="direction-btn west-btn" @onclick="() => SwitchFace('left')">see left</button> <!-- 魔方表格 --> <div style="width: 200px;"> <table class="table table-bordered"> <tbody> @for (var r = 0; r < 3; r++) { <tr> @for (int c = 0; c < 3; c++) { <td class="align-middle text-center" style="background-color: @currentFace[r, c]; color: white">@currentFace[r, c]</td> } </tr> } </tbody> </table> </div> <!-- 右侧按钮(东) --> <button class="direction-btn east-btn" @onclick="() => SwitchFace('right')">see right</button> <!-- 下方按钮(南) --> <button class="direction-btn south-btn" @onclick="() => SwitchFace('down')">see down</button> </div> @code { // 示例:存储不同魔方面的颜色数据 private Dictionary<string, string[,]> cubeFaces = new Dictionary<string, string[,]> { {"front", new string[,] {{"red", "red", "red"}, {"red", "red", "red"}, {"red", "red", "red"}}}, {"up", new string[,] {{"white", "white", "white"}, {"white", "white", "white"}, {"white", "white", "white"}}}, {"left", new string[,] {{"orange", "orange", "orange"}, {"orange", "orange", "orange"}, {"orange", "orange", "orange"}}}, {"right", new string[,] {{"green", "green", "green"}, {"green", "green", "green"}, {"green", "green", "green"}}}, {"down", new string[,] {{"yellow", "yellow", "yellow"}, {"yellow", "yellow", "yellow"}, {"yellow", "yellow", "yellow"}}} }; private string[,] currentFace; protected override void OnInitialized() { // 默认显示正面 currentFace = cubeFaces["front"]; base.OnInitialized(); } // 切换魔方面的方法 private void SwitchFace(string faceName) { if (cubeFaces.ContainsKey(faceName)) { currentFace = cubeFaces[faceName]; } } }
步骤2:添加Grid布局样式
在组件的<style>标签或全局样式文件中加入以下CSS:
.cube-container { display: grid; /* 定义网格结构:3列(左按钮、表格、右按钮),3行(上按钮、表格、下按钮) */ grid-template-columns: auto 200px auto; grid-template-rows: auto 1fr auto; /* 让整个容器水平居中(可选) */ justify-content: center; gap: 10px; /* 按钮与表格的间距 */ } /* 定位各按钮到对应网格区域 */ .north-btn { grid-column: 2; grid-row: 1; justify-self: center; /* 水平居中 */ } .west-btn { grid-column: 1; grid-row: 2; align-self: center; /* 垂直居中,与表格中间行对齐 */ } .east-btn { grid-column: 3; grid-row: 2; align-self: center; /* 垂直居中 */ } .south-btn { grid-column: 2; grid-row: 3; justify-self: center; /* 水平居中 */ } .direction-btn { padding: 8px 16px; cursor: pointer; }
核心原理说明
- CSS Grid通过
grid-template-columns和grid-template-rows划分出精确的网格区域,让按钮和表格各占其位 align-self: center属性让左右按钮在垂直方向上居中,刚好与魔方表格的中间行对齐- 上下按钮通过
justify-self: center实现水平居中,精准定位在表格的正上方/正下方 - 点击按钮时,通过
SwitchFace方法切换当前渲染的魔方面数据
内容的提问来源于stack exchange,提问作者quantum cat
相关产品推荐
相关产品推荐

