如何更改代码以创建3x3字段



我为tictactoe游戏编写了一个C#blazor程序。我有一个列表,其中包含由各个字段组成的整个匹配字段。

MatchField = new List<ElementOfMatchField>();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
MatchField.Add(new ElementOfMatchField(i, j));
}
}

我想使用html按钮和foreach循环打印它们:

<table id="tic-tac-toe">
<tbody>
<tr>
<td>
@foreach(var matchfield in MatchField)
{
<button>
</button>
}
</td>
</tr>

</tbody>
</table>

问题是,如果我这样打印,它将打印在一行,而不是3x3字段中。

如何更改代码以在3x3字段中打印它们?

MatchField = new List<List<ElementOfMatchField>> ();
for (int i = 0; i < 3; i++) {
var data = new List<ElementOfMatchField>();
for (int j = 0; j < 3; j++) {
data.Add(new ElementOfMatchField(i, j));
}
MatchField.Add(data);
}
<table id="tic-tac-toe">
<tbody>
<tr>
@foreach(var matchfield in MatchField) {
<td>
@foreach(var data in matchfield) {
<button>
</button>
}
</td>
}
</tr>
</tbody>
</table>

你可以使用css网格,如果你确定列的数量,你可以得到像这样的三列布局

<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 10px">    
@foreach(var matchfield in MatchField)
{
<button>
</button>
}            
</div>

您可以在按钮周围设置边距

grid-gap: 10

可以使用设置网格中的列数

grid-template-columns: 1fr 1fr 1fr

最新更新