HTML 适合窗口高度的响应式方形格子网格
问题描述
我试图创建一个响应式的方形格子网格(3×3和5×5),下面的代码能够正确创建一个随着窗口缩小而变小的方形格子网格。然而,我想限制整个容器的最大高度为浏览器窗口的高度,这意味着我必须限制单个方格的高度。但是,当我将min-height
和max-height
设置为方形时,宽度不会改变。
.square-container {
display: grid;
grid-template-columns:repeat(3,1fr);
grid-gap: 10px;
}
.square {
border: 1px solid;
border-radius: 5px;
aspect-ratio:1/1;
}
<div class="square-container">
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
<div class="square">4</div>
<div class="square">5</div>
<div class="square">6</div>
<div class="square">7</div>
<div class="square">8</div>
<div class="square">9</div>
</div>
解决方案
将该逻辑应用于容器
.square-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 1fr; /* equal rows*/
gap: 10px;
aspect-ratio: 1; /* make the container a square */
/* limit the width and height */
max-height: 100vh;
max-width: 100%;
/* center horizontally */
margin: auto;
}
.square {
border: 1px solid;
border-radius: 5px;=
/* full width and height*/
height: 100%;
width: 100%;
/**/
box-sizing: border-box;
}
body {
margin: 0;
}
<div class="square-container">
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
<div class="square">4</div>
<div class="square">5</div>
<div class="square">6</div>
<div class="square">7</div>
<div class="square">8</div>
<div class="square">9</div>
</div>