0

Is there a way to hide the bullet-point of <ul>...</ul> if there is only one item?

Example, here I want to have bullet-points:

<ul><li>foo</li><li>bar</li></ul>
* foo
* bar

Here, I don't want a bullet-point:

<ul><li>foo</li></ul>
foo

Is there a pure css solution?

guettli
  • 25,042
  • 81
  • 346
  • 663
  • have you seen the answer in : https://stackoverflow.com/questions/8720931/can-css-detect-the-number-of-children-an-element-has it might be helpful – Forrest Oct 10 '22 at 14:32

4 Answers4

2

You can use :only-child for that.

li {
  list-style: disc;
}

li:only-child {
  list-style: none;
}
<ul>
  <li>foo</li>
  <li>bar</li>
</ul>


<ul>
  <li>foo</li>
</ul>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
0

You can use :only-child or :nth-child(1):nth-last-child(1):

li:only-child {
  list-style-type: none;
}
<ul><li>foo</li><li>bar</li></ul>

<ul><li>foo</li></ul>

Unfortunately, you cannot target the ul, only the li with this method.

kelsny
  • 23,009
  • 3
  • 19
  • 48
0

Like this?

/* one item */

li:first-child:nth-last-child(1) {
  /* -or- li:only-child { */
  list-style: none;
}
2 items
<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

Only one
<ul>
  <li>foo</li>
</ul>

3 items
<ul>
  <li>foo</li>
  <li>bar</li>
  <li>bar</li>
</ul>

4 items
<ul>
  <li>foo</li>
  <li>bar</li>
  <li>bar</li>
  <li>bar</li>
</ul>
kiranvj
  • 32,342
  • 7
  • 71
  • 76
0

As others have astutely pointed out, you can use pseudo CSS classes.

A simple method if say you know the first bullet as in your example, foo, should always never have a bullet is first-child see: https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child

If it's the second, third, fourth, or every other one see: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

For targeting a specific <li> see above.

adamkolson
  • 11
  • 2