Home > database >  Target first level ul li elements only
Target first level ul li elements only

Time:09-01

This solution isn't going to work since I have no control over adding a class/id to the ul element: Get first level li from ul

Given that the parent ul has no id/class, can css be written to target only the first level li? If not, how could it be done?

This is the html:

<ul>
<li id="acomment-62"  data-bp-activity-comment-id="62">
    <div ></div>
   <ul>
        <li id="acomment-65"  data-bp-activity-comment-id="65">
            <div ></div>
            <div ></div>
            <div ></div>
        </li>
    </ul>
</li>

<li id="acomment-63"  data-bp-activity-comment-id="63">
    <div ></div>
   <ul>
        <li id="acomment-66"  data-bp-activity-comment-id="66">
            <div ></div>
            <div ></div>
            <div ></div>
        </li>
    </ul>
</li>

<li id="acomment-64"  data-bp-activity-comment-id="64">
    <div ></div>
   <ul>
        <li id="acomment-67"  data-bp-activity-comment-id="67">
            <div ></div>
            <div ></div>
            <div ></div>
        </li>
    </ul>
</li>

CodePudding user response:

I'm not sure how supported this is but you could apply the style to all li and then override that style using :is to target any descendant li

EG.

:is(li li) {
  color: initial;
}

li {
  color: red;
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>
    C
    <ul>
      <li>C1</li>
      <li>C2</li>
      <li>C3</li>
    </ul>
  </li>
  <li>D</li>
  <li>E</li>
</ul>

CodePudding user response:

You can do that with CSS alone. There's a few ways you can do it. Here is one of them and a working codepen so you can mess around with it yourself.

HTML

<ul>
<li>Item 1</li>
<li>Item with list 1
    <ul>
        <li>Sub 1</li>
        <li>Sub 2</li>
        <li>Sub 3</li>
    </ul>
</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item with list 2
    <ul>
        <li>Sub 1</li>
        <li>Sub 2</li>
        <li>Sub 3</li>
        <li>Sub List
            <ul>
                <li>Sub list item 1</li>
                <li>Sub list item 2</li>
                <li>Sub list item 3</li>            
            </ul>
        </li>
    </ul>
</li>
<li>Item 5</li>

CSS

li:first-of-type {
color: red;
}

li li:first-of-type {
    color: unset;
}
  • Related