该解决方案是完全未予以重视的+
组合子。
有了这个,我们可以给某个选择器一个样式,然后重置相同选择器的样式,如果它直接在之后再次出现。换句话说,只给这个类的第一个元素赋予样式。
.tags a { display: block; }
.tags a[href*="genre"] { margin-top: 1rem; }
.tags a[href*="genre"] + a[href*="genre"] { margin-top: 0; }
.tags a[href*="topic"] { margin-top: 1rem; }
.tags a[href*="topic"] + a[href*="topic"] { margin-top: 0; }
<div class="tags">
<h3>Tags</h3>
<a href="https://awesomechristianmusic.com/tag/artist-glad/" rel="tag">Artist: Glad</a>
<a href="https://awesomechristianmusic.com/tag/genre-a-capella/" rel="tag">Genre: A Capella</a>
<a href="https://awesomechristianmusic.com/tag/genre-hymns/" rel="tag">Genre: Hymns</a>
<a href="https://awesomechristianmusic.com/tag/topic-faith/" rel="tag">Topic: Faith</a>
<a href="https://awesomechristianmusic.com/tag/topic-god/" rel="tag">Topic: God</a>
<a href="https://awesomechristianmusic.com/tag/topic-prayer/" rel="tag">Topic: Prayer</a>
</div>
或者,如果你确信不会有任何东西,除了元素的DIV一样,你可以缩短这样的CSS的东西:
.tags a {display: block;}
.tags a:not([href*="genre"]) + a[href*="genre"],
.tags a:not([href*="topic"]) + a[href*="topic"] {margin-top: 1rem;}
你不能使用:最后一种类型。您将需要修改您的HTML以适合您的使用情况。就像将每种类型的元素放入其自己的容器中,然后为每个容器的最后一个子元素设计样式。 – BoltClock
或者你可以保持HTML不变,并使用'+'combinator ... –