Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

html - 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 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...