第一种方法: flex布局
布局:
<div class="square">
<div class="square-inner">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
</div>
样式:
.square{
position: relative;
width: 80%;
padding-bottom: 80%; /* padding百分比是相对父元素宽度计算的 */
}
.square-inner{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%; /* 铺满父元素容器,这时候宽高就始终相等了 */
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.square-inner>div{
width: calc(100% / 3);
height: calc(100% / 3);
border: 5px solid #fff;
background: red;
box-sizing: border-box;
}
第二种: grid布局
布局:
<div class="square">
<div class="square-inner">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
</div>
样式:
.square{
position: relative;
width: 80%;
padding-bottom: 80%;
}
.square-inner{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: grid;
grid-template-columns:repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
grid-gap: 2%;
grid-auto-flow:column;
}
.square-inner>div {
background: red;
}