문제

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 is what I was trying to do and it was working until I add the heading tag.

.pubs .newsdate {
    border-top:1px solid rgb(255,179,0);
}
.pubs:first-child .newsdate {
    border:none;
}
<section class="content">
    <h2>News</h2> //issue
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
</section>

The first border was being removed properly until I added the heading (h2) tag. Then, the pseudo selector stopped working. What could have happened?

도움이 되었습니까?

해결책

.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).

다른 팁

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

Example Here

.pubs:first-of-type .newsdate {
    border:none;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top