CSS网格布局调整大小



我正在做一个学校项目,这是一个棋盘游戏,我必须在棋盘的一个区域放置多个玩家,我想用网格布局来制作,但我无法找到正确的位置。

我想确保,如果容器中只有一个div,它会占用整个空间。如果容器中有两个div,那么它会占用一半的空间,两个项目并排放置。如果它的内部有三个四个div,那么每行有两个div。

我当前的代码是:

#board td{
background-color: black;
height: 50px;
width: 50px;
}
#board td .playersDiv {
height: 100%;
width: 100%;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
#board td .playersDiv div{
background-image: url('red.png');
width: 100%;
height: 100%;
background-size: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table id="board">
<tr>
<td>
<div class="playersDiv">
<div></div>
<div></div>
<div></div>
</div>
</td>
</tr>
</table>
</body>
</html>

如果我理解正确:

  • 您的代码已经适用于playersDiv内的2、3和4个DIV
  • 当只有1个DIV时,它需要跨越2列。这可以使用:only-child选择器和grid-column属性来实现

#board td {
background-color: black;
height: 50px;
width: 50px;
}
#board td .playersDiv {
height: 100%;
width: 100%;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
#board td .playersDiv div {
/* I've change these lines so we can see the DIVs in the snippet */
border: 1px solid red;
}
#board td .playersDiv div:only-child {
grid-column: span 2;
}
<table id="board">
<tr>
<!-- 1 div -->
<td>
<div class="playersDiv">
<div></div>
</div>
</td>

<!-- 2 div -->
<td>
<div class="playersDiv">
<div></div>
<div></div>
</div>
</td>

<!-- 3 div -->
<td>
<div class="playersDiv">
<div></div>
<div></div>
<div></div>
</div>
</td>

<!-- 4 div -->
<td>
<div class="playersDiv">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</td>
</tr>
</table>

最新更新