我正在构建一个游戏,其棋盘位于左侧,得分区域位于右侧。我希望当浏览器展开时,板上的各个图 block 保持正方形。到目前为止,它们在宽度方向上增长,但在高度上没有增长。
开始设置:
调整浏览器窗口大小时如何保持图 block 为正方形?
这是 .html 文件的相关部分:
<div class="board">
<div class="square" id="square1">5</div>
(...and 15 more like the above line...)
</div>
<div class="score">
<h1>Score:</h1>
<h2>0</h2>
</div>
绘制图 block /方 block 的 JavaScript 函数:
function drawSquares() {
for(let i = 1; i < 17; i++) {
const square = document.createElement('div')
square.setAttribute('class', 'square')
square.setAttribute('id', ('square'+i))
square.innerText = randArr[i-1]
board.appendChild(square)
}
}
以及我的完整 CSS,因为我不确定要更改哪一部分:
body {
display: flex;
}
.board {
height: 370px;
width: 70%;
display: flex;
flex-wrap: wrap;
background-color: rgb(172, 170, 170);
padding: 1%;
margin: 1%;
}
.score {
background-color: rgb(172, 170, 170);
margin: 1%;
width: 30%;
}
.square {
height: 23%;
width: 23%;
background-color: rgb(121, 120, 117);
margin-left: 1%;
margin-right: 1%;
justify-content: center;
align-items: center;
font-size: 5vh;
color: rgb(121, 120, 117);
}
h1, h2 {
text-align: center;
}
(.square CSS 选择器设置图 block 样式)
最佳答案
要在响应式设计中保持宽高比,使用与宽度
相同的高度
并不像您所看到的那样。高度取决于具有显式高度设置的包含 block ,但在响应式网格中,我们不需要固定高度。
相反,您可以使用填充,因为它将以与宽度相同的方式计算容器的百分比。您可以将 .square
类更改为:
.square {
width: 23%;
height:0;
padding-bottom: 23%;
/* Rest of your CSS... */
}
它的作用:
- 我们可以将
padding-bottom
设置为与宽度相同 - 在本例中为 23% - 以形成正方形 - 将高度设置为 0,以便 padding-bottom 是唯一增加高度的东西
这为您提供了一个完全响应式的网格,无论屏幕尺寸如何,它都保持相同的纵横比。
工作片段:
function drawSquares() {
for(let i = 1; i < 17; i++) {
const square = document.createElement('div')
square.setAttribute('class', 'square')
square.setAttribute('id', ('square'+i))
square.innerText = [i];
board = document.getElementsByClassName('board')
board[0].appendChild(square)
}
}
drawSquares();
body {
display: flex;
}
.board {
height: auto;
width: 70%;
display: flex;
flex-wrap: wrap;
background-color: rgb(172, 170, 170);
padding: 1%;
margin: 1%;
}
.score {
background-color: rgb(172, 170, 170);
margin: 1%;
width: 30%;
}
.square {
width: 23%;
height:0;
padding-bottom: 23%;
background-color: rgb(121, 120, 117);
margin-left: 1%;
margin-right: 1%;
margin-bottom: 2%;
justify-content: center;
align-items: center;
font-size: 5vh;
color: rgb(121, 120, 117);
color: #fff;
}
h1, h2 {
text-align: center;
}
<div class="board">
</div>
<div class="score">
<h1>Score:</h1>
<h2>0</h2>
</div>
在上面的例子中,我还:
- 从
.board
中删除了height: 370px;
,因为它没有随方 block 一起增长 - 为
.squares
添加了下边距,以保持间距均匀 - 将数字设为白色,以便我可以验证它们不会影响大小
关于css - 如何让网格中的方 block 在屏幕宽度变化时均匀增长和收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63608496/