Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

CSS3 Pseudo-headache

DZone's Guide to

CSS3 Pseudo-headache

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

So, the other day I was building a list for an HTML page.  I needed to change the font color of the last item in the list having the top CSS class.

Here is my list, and its equivalent HTML structure with classes:

CSS Pseudo - Sample 1

Since what I wanted to do was merely style-related, I tought of only using CSS for it. After all, how hard could it be!? RIGHT!?

Anyways, after choosing to use CSS pseudo selectors for it, my first attempt was something like this:

ul li.list-item.top:last-child {
    color: red;
}

Makes perfect sense, right? I mean: “from the list, select the last child element with the list-item top class and apply style to it.” Well, not so fast… Turns out it doesn’t work that way.

However, if you add top to the only element that does not have it, everything magically works. Why is this? Apparently, CSS pseudo selectors handle classes a little bit different than I thought. My CSS selector reads a little more like: “from the list, select the last child element and apply the style IF it has the list-item top class.” This means that if the last element in the list does not have that class, it will just skip it.

Of course, I could not style my list without using JavaScript or adding extra CSS classes to the element. It would be awesome if that CSS selector worked, since is not the first time I’ve had to do something like that. Sigh…

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}