majidR majidR - 6 months ago 9
HTML Question

How to style two groups of <li> in a single line?

I want to have two groups of list items in one line, so that one group starts from left to right and another from right to left; like so:

[li1 li2 li3]........................................[li6 li5 li4]


I have tried this:



li{
display:inline;
}
#left{
float:left;
}
#right{
float:right;
direction:rtl;
}

<ul>
<span id="left">
<li> item1</li>
<li> item2</li>
<li> item3</li>
</span>
<span id="right">
<li> item4</li>
<li> item5</li>
<li> item6</li>
</span>
</ul>





The output works, but the code is not valid, since it use a
<span>
directly under a
<ul>
.

What's the valid code for this?

Answer

You are correct about <span> directly under a <ul> being invalid. Here's a few solutions:

Give float the <li> element directly.

li{
  display:inline;
  float: left;
 }
.right{
  float:right;
  direction:rtl;
 }
<ul>
    <li> item1</li>
    <li> item2</li>
    <li> item3</li>
    <li class="right"> item4</li>
    <li class="right"> item5</li>
    <li class="right"> item6</li>
</ul>


Use nth-of-type or nth-child.

I think this is a nice and clean solution. Though you'd have to change the css if you add/remove items in the list:

li {
  display: inline;
  float: left;
}
li:nth-of-type(n+4) {
  float: right;
}
<ul>
  <li class="left">item1</li>
  <li class="left">item2</li>
  <li class="left">item3</li>
  <li class="right">item4</li>
  <li class="right">item5</li>
  <li class="right">item6</li>
</ul>

Also, it looks like you can omit the direction: rtl from your code.

Comments