How to select a specific element in a <ul> list without nth-child?

4.2k views Asked by At

So I'm using the Stylish addon to edit a web page to my liking. There is a ul element and I want some of the items to become icons, and some of them to disappear. So I set it all up and it works fine. However, sometimes the website adds one more element to the list and screws everything up because I'm using nth-child selectors and obviously when the number of each element changes it breaks my css.

So I was wondering if there is a better way to select the li elements other than nth-child? A more specific way? Each of them has a header...is there some way of using that to select them?

Another idea I just had is maybe I could count backwards from the last li because the new list item is added towards the top...is there a way to do that?

2

There are 2 answers

0
bob On BEST ANSWER
<style>
li:last-child {
 /* style goes here*/
}
</style>

will get you to the last element of the list if that is what you are referring to

1
Radames E. Hernandez On

You can use another selector like a attribute for example the data attribute.

Also, you can use other selectors for example a class or id

HTML:

<ul>
    <li id="id-1" class="id-1" data-id="1">Element</li>
</ul>

CSS:

li#id-1{
    //something...
}
// or
li.id-1{
    // something...
}
// or
li[data-id="1"]{
    // something...
}

Updated:

CSS:

li:first-of-type{
    // something...
}
// or

li:last-of-type{
    // something...
}

Regards