假设我们有一个这样的 html 列表:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
...
<li>10</li>
</ul>
如何使用 css 和/或 java 脚本使浏览器显示如下(以四个为一组,组之间留有一定的间距):
1 2 5 6 9 10
3 4 7 8
只需使用column-count
,float
并将width
包装在可以应用规则ul
的父元素中:column-count
.colWrap {
-webkit-column-count: 3;
-moz-column-count: 3;
-o-column-count: 3;
-ms-column-count: 3;
column-count: 3;
}
li {
float: left;
width: 50%;
}
调整后的 HTML:
<div class="colWrap">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
参考:
column-count
您可以为此使用 css3属性:
像这样写:
.colWrap {
-webkit-column-count: 3;
-moz-column-count: 3;
-o-column-count: 3;
-ms-column-count: 3;
column-count: 3;
-webkit-column-width:20px;
-moz-column-width:20px;
}
li {
display:inline;
}
div{
width:120px;
}
在这里使用 jQuery 的替代方式..(现场演示)
var ul = $('ul'),
lis = $('ul li');
lis.each(function (index) {
if(index % 4 === 0) {
ul.append($('<ul />'));
}
ul.find('ul').eq(~~(index / 4)).append($(this));
});
和 CSS
ul ul {
float: left;
width: 50px;
margin-right: 30px;
}
ul li {
list-style-type: none;
float: left;
width: 50%;
}
您可以通过将“ul”替换为符合您需求的表格来尝试。 看演示
您只需使用 css 或不同的 html 标签根据您的需要自定义此演示。
JavaScript
$(function(){
$("ul").each(function(){
var oh = "<table><tr>";
for(i=0;i<this.children.length;i++){
oh += "<td>"+this.children[i].innerHTML+"</td>";
if(i%2==1){
oh+="</tr>";
if(i%4==3){
oh+="</table><table><tr>";
} else {
oh+="<tr>";
}
}
}
oh += "</tr></table>";
this.outerHTML = oh;
});
});
编辑
CSS column-count也有可能,但这并不适用于所有浏览器。请参阅何时可以使用。所以我的是一个后备版本,应该可以在更多的浏览器中使用。
使用 html 表格
<table>
<tr>
<td></td>
</tr>
</table>
并更改表格的边框特征以隐藏它。希望这可以帮助。