Skip to content Skip to sidebar Skip to footer

First-child Pseudo Selector Issue With Heading Tag

I got stuck when designing a dynamic page of news today when I added a heading tag at the beginning of my section and the first-child of a p tag inside a div stopped working. This

Solution 1:

.pubs:first-child looks for a class of pubsthat is also the first child of its parent element (in this case, parent element is class content. Once you add an h2 element before the first pubs class, then pubs is no longer the first child, but the second.

Try .pubs:first-of-type instead:

.pubs:first-of-type .newsdate {
    border: none;
}

The :first-of-type pseudo-selector will look for the first type of whichever class or ID or element you prepend it with. By this, I mean that it doesn't matter if an element (div), a class (.pub), or an ID (#pub) comes before the pseudo-selector (each one is valid). Although it wouldn't make much sense to use an ID, since those are supposed to be unique.

Also notice I said first type, not first instance (two people have already commented (one deleted their comment) confusedly about what I'm saying). For instance, if you have class .pubs on three div elements and two p elements, your :first-of-type pseudo-selector would apply to the first .pubs div element AND the first .pubs p element.

So first-of-type pseudo-selector can apply to multiple elements, depending on how you use it.

If you think about it, this is a better solution than when you first had it working, because this solution looks specifically for the very first instance of the .pubs class, whereas your example only works circumstantially (when there isn't anything before .pubs).

Solution 2:

You can use :first-of-type to avoid this.

Example Here

.pubs:first-of-type .newsdate {
    border:none;
}

Post a Comment for "First-child Pseudo Selector Issue With Heading Tag"