I'm trying to create a horizontal UL which always shows 3 items per line. The tricky part is that the items can be of varying widths. For example:
我正在尝试创建一个水平UL,每行总共显示3个项目。棘手的部分是物品的宽度可以不同。例如:
<ul class="items">
<li>
<input type="checkbox" id="work" />
Work items
</li>
<li>
<input type="checkbox" id="shopping" />
Shopping
</li>
<li>
<input type="checkbox" id="financial" />
Financial Information & Tips
</li>
</ul>
etc.
等等
I want to do it so its essentially like using a table, where it always shows 3 items per line, and the checkbox of each item is always on the same line as its text.
我想这样做,所以它基本上就像使用一个表,每行总是显示3个项目,每个项目的复选框始终与文本在同一行。
How can I do it?
我该怎么做?
Here's the current code I'm using, but it doesn't show the items evenly, often the last checkbox ends up on line 1 and the text is pushed to the next line.
这是我正在使用的当前代码,但它没有均匀显示项目,通常最后一个复选框在第1行结束,文本被推送到下一行。
ul.items
{
text-align: center;
list-style-type: none;
width: 400px;
}
ul.items li
{
display: inline;
}
2 个解决方案
#1
4
I like to use float for this
我喜欢用float来做这件事
ul.items
{
text-align: center;
list-style-type: none;
width: 400px;
}
ul.items li
{
float: left;
display: inline;
}
.clear { clear: both; }
with this html:
用这个HTML:
<ul class="items">
<li>
<input type="checkbox" id="work" />
Work items
</li>
<li>
<input type="checkbox" id="shopping" />
Shopping
</li>
<li>
<input type="checkbox" id="financial" />
Financial Information & Tips
</li>
<li class="clear"></li>
</ul>
Demo here: http://jsfiddle.net/hG3Us/
在这里演示:http://jsfiddle.net/hG3Us/
#2
13
Try the CSS nth-child
selector. Works regardless of the width.
尝试CSS nth-child选择器。无论宽度如何都可以工作。
I also removed your display:inline
rule and replaced it with a float:left;
.
我还删除了你的显示:内联规则并用float:left;替换它。
jsFiddle示例
ul.items li:nth-child(3n+4) {
clear:left;
float:left;
}
For more info on nth-child
, see https://developer.mozilla.org/en-US/docs/CSS/:nth-child
有关nth-child的更多信息,请参阅https://developer.mozilla.org/en-US/docs/CSS/:nth-child
#1
4
I like to use float for this
我喜欢用float来做这件事
ul.items
{
text-align: center;
list-style-type: none;
width: 400px;
}
ul.items li
{
float: left;
display: inline;
}
.clear { clear: both; }
with this html:
用这个HTML:
<ul class="items">
<li>
<input type="checkbox" id="work" />
Work items
</li>
<li>
<input type="checkbox" id="shopping" />
Shopping
</li>
<li>
<input type="checkbox" id="financial" />
Financial Information & Tips
</li>
<li class="clear"></li>
</ul>
Demo here: http://jsfiddle.net/hG3Us/
在这里演示:http://jsfiddle.net/hG3Us/
#2
13
Try the CSS nth-child
selector. Works regardless of the width.
尝试CSS nth-child选择器。无论宽度如何都可以工作。
I also removed your display:inline
rule and replaced it with a float:left;
.
我还删除了你的显示:内联规则并用float:left;替换它。
jsFiddle示例
ul.items li:nth-child(3n+4) {
clear:left;
float:left;
}
For more info on nth-child
, see https://developer.mozilla.org/en-US/docs/CSS/:nth-child
有关nth-child的更多信息,请参阅https://developer.mozilla.org/en-US/docs/CSS/:nth-child