Do not select, dynamically, always the last li in the hierarchy

Asked

Viewed 306 times

0

Note the HTML and CSS below.

This is the initial CSS

ul ul li:nth-last-of-type(2){
  background: #ff0000;
}

<ul>
  <li>bla
    <ul>
      <li>bla bla
        <ul>
          <li>bla bla bla</li>
          <li>Gostaria que não fosse selecionado</li>
          <li>bla bla bla</li>
        </ul>
      </li>
      <li>Selecionado</li>
      <li>bla bla</li>
    </ul>
  </li>
  <li>bla
    <ul>
        <li>Selecionado</li>
        <li>bla bla</li>
      </ul>
  </li>
  <li>bla</li>
</ul>

The manual solution would be to do this

ul ul ul li:nth-last-of-type(2){
  background: initial;
}

But I didn’t want to do it like that. Supposing I added to ul deeper in the hierarchy the li down below.

<li>
  bla bla bla
  <ul>
    <li>Agora esse não deve mais ser selecionado</li>
    <li>Bla bla bla bla</li>
  </ul>
</li>

ul ul ul ul li:nth-last-of-type(2){
  background: initial;
}

That is, this CSS is not sustainable. Every new node on ul I will need to maintain CSS every time by adding a new ul in the hierarchy to restart the property. How do I make it dynamic?

  • 3

    How about adding a class to those li different?

  • I was gonna comment on what @Lucas said

  • 1

    What is the criteria for knowing which one is going to be different? It might be interesting to detail the ultimate goal, in addition to the way you’re trying to do, so you don’t fall into a XY problem.

  • So people, the criterion I tried to inform in the description. I always read the deeper in the hierarchy should not be selected. If I add it to HTML, I don’t want to have to touch CSS. You understand?

2 answers

1

And if you did something like this?

li > ul > li {
    background: #ff0000;
}

li > ul > li:first-child,
li > ul > li:last-child {
    background: initial;
}
  • I will test and report. Thank you.

1

Use id or class selectors'

html

<li class="lista1">
</li>

or

<li id="lista2">
</li>

css

.lista1 {color:blue}
'#lista2 {color:green}

Every time you identify a tag with these selectors it will assume the code properties in css.

See if it helps
http://www.w3schools.com/css/css_selectors.asp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.