ua_boaz ua_boaz - 1 year ago 55
CSS Question

align first two elements in the unordered list items inline and the rest one per line

So I have this list which I am trying to arrange.

I want to show the first two

elements in one line (inline) and other elements in separate rows.

I have tried adding display table > table-cell css properties to first two elements, but it just indents the other
elements to second row.

Is there a cleaner way of doing it?

<li> Check All </li>
<li> Uncheck All </li>
<li> Option A </li>
<li> Option B </li>
<li> Option C </li>
<li> Option D </li>
<li> Option E </li>
<li> Option F </li>
<li> Option G </li>

Answer Source

Apply a display: inline-block for the first two list-items, e.g.

li:nth-child(-n + 2) {
   display: inline-block;

As a general solution: if you need to match the first k list-items, the selector has to be written in the form of li:nth-child(-n + k)

Codepen example

As a side note, if using a negative index is not intuitive to you, you can also revert the logic and apply that property to the elements that are not :nth-child(n + k + 1), like so

li:not(:nth-child(n + 3)) {
  display: inline-block;

but in my opinion is less readable and the logic is quite convoluted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download