Css – not:first-child selector

csscss-selectors

I have a div tag containing several ul tags.

I'm able to set CSS properties for the first ul tag only:

div ul:first-child {
    background-color: #900;
}

However, my following attempts to set CSS properties for each other ul tag except the first one don't work:

div ul:not:first-child {
    background-color: #900;
}

div ul:not(:first-child) {
    background-color: #900;
}

div ul:first-child:after {
    background-color: #900;
}

How can I write in CSS: "each element, except the first"?

Best Answer

One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):

div ul:not(:first-child) {
    background-color: #900;
}

If you need to support legacy browsers, or if you are hindered by the :not selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:

Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:

div ul {
    background-color: #900;  /* applies to every ul */
}

div ul:first-child {
    background-color: transparent; /* limits the scope of the previous rule */
}

When limiting the scope use the default value for each CSS attribute that you are setting.