如何基于flex或grid建立动态网格 [英] How to set up a dynamic grid based on flex or grid
问题描述
我想创建一个动态网格系统,其行为应如下所示:首先,当只有一项时,其宽度和高度应为100%.
I want to create a dynamic grid system that should behave like this: first when there is only 1 item it should have a width and height of 100%.
将第二个子项动态添加到网格后,其高度应为100%,两个项目的宽度均应为50%.
When the second child has been dynamically added to the grid it should have a height of 100% and the 2 items both 50% width.
添加了THIRD项目后,前两个项目的高度应为0f 50%,宽度为50%,第三个项目的高度应为50%,宽度为100%.
When the THIRD item has been added the first 2 items should have a height 0f 50% and a width of 50%, the third item should have a height of 50% and a width of 100%.
第四项的宽度应再次为50%,高度为50%.
Fourth item should then again have a width of 50% and height 50%.
第五个项目再次为100%宽度,所有项目的高度应为33,33%.无论添加多少项目,网格都应始终以相同的方式运行.
fifth item again 100% width and all the items should have 33,33% height. No matter how many items are added the grid should always behave the same way.
目前我有:
const StyledVideoContainer = styled.div`
${({ number }) => `
display: grid;
grid-template-columns: repeat(${number}, 1fr);
grid-template-rows: repeat(auto-fill, 100%);
.videoContent {
flex-grow: 1;
}
`}
`;
推荐答案
您可以使用flexbox进行操作,如下所示:
You can do it with flexbox like below:
.container {
border: 1px solid;
display: inline-flex;
flex-wrap: wrap; /* enable the wrap */
margin:5px;
vertical-align: top;
width: 150px;
height: 150px;
}
.container>* {
flex-basis: 50%; /* width = 50% */
flex-grow: 1; /* grow if alone in the last row */
border: 1px solid red;
box-sizing: border-box;
}
<div class="container">
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
使用CSS网格会有些棘手,但是您可以按照以下方式进行操作:
It would be a bit tricky with CSS grid but you can do it like below:
.container {
border: 1px solid;
display: inline-grid;
grid-template-columns:1fr 1fr; /* 2 columns */
grid-auto-rows:1fr; /* equal rows */
margin:5px;
vertical-align: top;
width: 150px;
height: 150px;
}
.container>* {
border: 1px solid red;
}
.container>*:nth-child(odd):last-child {
grid-column:span 2; /* take 2 columns */
}
<div class="container">
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
这篇关于如何基于flex或grid建立动态网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!