Html 如何为每个 x 列表在 ul 水平列表中换行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14621656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:21:56  来源:igfitidea点击:

How to make line break in ul horizontal list for every x list?

htmlcsshtml-lists

提问by Wakanina

I have horizontal dynamic ullist build by PHP like this:

我有ul这样的 PHP 构建的水平动态列表:

List1 List2 List3 List4 List5 List6 List7 List8 List9 List10

Is there a way to make new line every 3 lists? So, the result will look like this:

有没有办法每 3 个列表创建新行?因此,结果将如下所示:

List1 List2 List3

List4 List5 List6

List7 List8 List9

List10

I know I can adjust the ulwidth to make my lists look like above.

我知道我可以调整ul宽度使我的列表看起来像上面那样。

But what I want is to make new line for every 3 lists. Is PHP, CSS, or JavaScript can do this? Anyone can help?

但我想要的是为每 3 个列表创建新行。PHP、CSS 或 JavaScript 可以做到这一点吗?任何人都可以帮忙吗?

采纳答案by Панайот Толев

If you don't have fixed sizes of you list items you can do it simple with jQuery:

如果您没有固定大小的列表项,您可以使用 jQuery 简单地完成:

$('li:nth-child(3n)').next().css({'clear': 'both'});

This takes every third element, and add clear to the next one. That's way .. no matter what size is your list item it will take the next after every 3th element to new line.

这需要每三个元素,并为下一个添加清除。就是这样..无论你的列表项有多大,它都会在每 3 个元素之后将下一个元素带到新行。

回答by Aidan Ewen

How about just -

怎么样只是——

li {
  width: 33%;
  float: left;
  list-style: none;
}

Setting the width of each lielement to one third of the available space means we can fit three floated li's on every line, before the browser pushes the next one onto a new line.

将每个li元素的宽度设置为可用空间的三分之一意味着我们可以li在每一行上放置三个浮动的,然后浏览器将下一个推到新的行上。

I guess you could probably swap the float: leftstatement for display: inlineto get the same effect.

我想你可能可以交换float: left语句display: inline以获得相同的效果。

回答by hsz

You have to set every <li>width - for example width: 100px;and for <ul>set width: 300px.

您必须设置每个<li>宽度 - 例如width: 100px;<ul>set width: 300px

ul, li {
  margin: 0;
  padding: 0;
}
ul {
  width: 300px;
}
li {
  width: 100px;
  float: left;
  list-style: none;
}

回答by Claudio G?tz

As Панайот Толев mentioned in his post but only with CSS3:

正如 Панайот Толев 在他的帖子中提到的,但仅使用 CSS3:

li:nth-child(3n) + li
{
    clear:both;
}

Select every 3rd element and add a clear:both to the next following list element

选择每个第三个元素并将 clear:both 添加到下一个列表元素

回答by Vlad Preda

If you want to do this with PHP and not css (as @hsz suggested), you can split it in ul's that have a maximum of 3 li's in them

如果您想使用 PHP 而不是 css(如@hsz 建议的那样)执行此操作,您可以将其拆分ul为最多包含 3 个的li's

<ul class="...">
<?php
$i = 1;
$array = (/* 10 items */);
foreach ($array as $item) {
    if ($i % 3 == 0) { echo '</ul><ul>'; }
    echo "<li>{$item}</li>";
    $i ++;
}
?></ul>