First-child pseudo selector issue with heading tag

后端 未结 2 1901
再見小時候
再見小時候 2020-12-21 15:07

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

相关标签:
2条回答
  • 2020-12-21 15:11

    .pubs:first-child looks for a class of pubs that 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).

    0 讨论(0)
  • 2020-12-21 15:22

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

    Example Here

    .pubs:first-of-type .newsdate {
        border:none;
    }
    
    0 讨论(0)
提交回复
热议问题