首页 > 解决方案 > 块内类的第一个实例的 CSS 选择器

问题描述

我正在尝试定位块中类的第一个实例。

.ContactPage-details div > .ContactPage-title ~ .ContactPage-title:not(:first-child) {
	background: none;
}

.ContactPage-details div > .ContactPage-title {
    background: red;
    color: white;
}
<div class="ContactPage-details">
  <div class="ContactPage-telephone">
    <h3 class="ContactPage-title">The First paragraph.</h3>
  </div>
  <div class="ContactPage-emailAddress">
    <h3 class="ContactPage-title">The Second paragraph.</h3>
  </div>
  <div class="ContactPage-address">
    <h3 class="ContactPage-title">The Third paragraph.</h3>
  </div>
</div>

我正在尝试瞄准<h3 class="ContactPage-title">The First paragraph.</h3>

第一个 h3 父级可以更改,它可能不一定总是.ContactPage-telephone如此,所以我不能直接定位它,因为它会有所不同,具体取决于它们是否在数据库中列出了电话号码。

这是我当前尝试针对的第一个实例的 cssContactPage-title

此刻,所有h3的都有一个红色的背景和白色的颜色。

ContactPage-title有没有一种方法可以在不使用 javascript的情况下定位第一个实例?

标签: htmlcsscss-selectors

解决方案


要回答您对问题的描述:

不,CSS 有:first-child:first-of-type但没有:first-of-class

但是,您的示例代码看起来像是您实际上想要定位.ContactPage-title块中第一个孩子的孩子。

那将是:

.ContactPage-details > :first-child > .ContactPage-title {}

推荐阅读