简体   繁体   中英

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

I have horizontal dynamic ul list build by PHP like this:

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:

List1 List2 List3

List4 List5 List6

List7 List8 List9

List10

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

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

How about just -

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

Setting the width of each li element 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.

I guess you could probably swap the float: left statement for display: inline to get the same effect.

If you don't have fixed sizes of you list items you can do it simple with 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.

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

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

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

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

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

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

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM