我希望输出看起来像下面的jsfiddle:
然而,对于两件事情,这是硬编码的: - 行数为三 - 列大小为3(行大小为3)基本上我想知道是否有一个优雅的解决方案,为可变数量的内联元素设置零外边距 - 为了响应式设计。
以下代码:
html
<ul>
<li></li><li>
</li><li>
</li><li>
</li><li>
</li><li>
</li><li>
</li><li>
</li><li>
</li>
</ul>
CSS
ul,li {
margin: 0;
padding: 0;
}
ul {
background-color: black;
width: 140px;
}
ul > li {
display: inline-block;
list-style-type: none;
vertical-align:top;
background-color: gray;
width: 40px;
height: 40px;
}
ul > li:nth-child(1n + 4) {
margin-top: 10px;
}
ul > li:nth-child(3n + 2) {
margin-left: 10px;
margin-right: 10px;
}
答案 0 :(得分:1)
您可以使用javascript动态生成代码,而不是使用硬编码的html。需要知道的参数是:
以下是我写的代码:
<强> HTML 强>
<div></div>
<强> CSS 强>
div {
background: #000;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
.innerCell {
float: left;
background: #999;
}
<强>的JavaScript 强>
var cell = 12;
var cell_dimension = 50;
var margin = 10;
var columns = 3;
var rows = Math.ceil(cell/columns);
var container_dimension_width = cell_dimension*columns + margin*(columns-1);
var container_dimension_height = cell_dimension*rows + margin*(rows-1);
var list_dimension_width = (cell_dimension+margin)*columns;
var list_dimension_height = (cell_dimension+margin)*rows;
var output = document.getElementsByTagName('div')[0];
output.style.height = container_dimension_height+'px';
output.style.width = container_dimension_width+'px';
var list = document.createElement('ul');
output.appendChild(list);
list.style.height = list_dimension_height+'px';
list.style.width = list_dimension_width+'px';
for(var i=0;i<cell;i++) {
var innerCell = document.createElement('li');
innerCell.setAttribute('class','innerCell');
list.appendChild(innerCell);
document.getElementsByTagName('li')[i].style.height = cell_dimension+'px';
document.getElementsByTagName('li')[i].style.width = cell_dimension+'px';
document.getElementsByTagName('li')[i].style.marginRight = margin+'px';
document.getElementsByTagName('li')[i].style.marginBottom = margin+'px';
}
您可以在此处试用JSFiddle:http://jsfiddle.net/amitdatta/r5x5Y/ 尝试替换上面提到的四个参数!