【发布时间】:2021-09-16 16:32:16
【问题描述】:
我需要一个解决方案,最有可能使用 flexbox,用于需要灵活的内容网格,具体取决于在 CMS 中创建的对象数量。我知道 flex 可以用来创建每个单独的选项,如下所示,但是有没有一种方法可以在不知道 div 总数的情况下使用 flex 来显示布局?
【问题讨论】:
标签: html css bootstrap-4 flexbox
我需要一个解决方案,最有可能使用 flexbox,用于需要灵活的内容网格,具体取决于在 CMS 中创建的对象数量。我知道 flex 可以用来创建每个单独的选项,如下所示,但是有没有一种方法可以在不知道 div 总数的情况下使用 flex 来显示布局?
【问题讨论】:
标签: html css bootstrap-4 flexbox
有没有办法在不知道 div 总数的情况下使用 flex 显示布局?
只需将flex:auto 应用于所有孩子divs:
.row{
display:flex;
flex-wrap:wrap;
width:330px;
}
.col{
background-color:#D0D1D2;
width:100px;
height:100px;
margin:5px;
flex:auto;
}
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
让您选择divs 数量的演示示例:
range.addEventListener('input', function(){
row.innerHTML = '<div class="col"></div>'.repeat(this.value);
this.nextElementSibling.textContent = this.value;
})
.row{
display:flex;
flex-wrap:wrap;
width:330px;
}
.col{
background-color:#D0D1D2;
width:100px;
height:100px;
margin:5px;
flex:auto;
}
<div class="row" id="row">
<div class="col"></div>
</div>
<input type="range" id="range" value="1" min="1" max="10"><output>1</output>
【讨论】:
// You can remove this unless you want to
// programmatically add or remove divs
var noOfDivs = 1;
function addDiv() {
noOfDivs++;
render();
}
function removeDiv() {
noOfDivs = Math.max(0, noOfDivs - 1);
render();
}
function render() {
document.getElementById("container").innerHTML = '';
for(var i = 0; i < noOfDivs; i++) {
document.getElementById("container").innerHTML += "<div class = 'inner'></div>"
}
}
#container {
display: flex;
flex-flow: row wrap;
margin-bottom: 5px;
}
#container div.inner {
background: #aaa;
height: 100px;
width: 100px;
margin: 2px;
flex: auto;
}
/*Remove these syles later they are just for the buttons*/
#add-box {
position: fixed;
left: 10px;
top: 10px;
font-size
}
#remove-box {
position: fixed;
left: 80px;
top: 10px;
font-size
}
<div id='container'>
<div class='inner'></div>
</div>
<button onclick='addDiv()' id = 'add-box'>Add box</button>
<button onclick='removeDiv()' id = 'remove-box'>Remove box</button>
【讨论】: