html - CSS:定位每个类的第一个对象

标签 html css

我有一个包含 2 个可能类别的标签列表:P1 和 P2。我想将 CSS 应用于每个类的第一项。它在我的元素和 fiddle 中都不起作用

这是为什么?

.A>.B>.C>.P1:first-child {
  font-weight: bold;
}

.A>.B>.C>.P2:first-child {
  font-style: italic;
}

;
<div class="A">
  <div class="B">
    <div class="C">
      <p class='P1'>
        "JAJA P1"
      </p>
      <p class='P1'>
        "JAJA P1"
      </p>
      <p class='P2'>
        "JAJA P2"
      </p>
      <p class='P2'>
        "JAJA P2"
      </p>
    </div>
  </div>
</div>

最佳答案

:first-child 表示“该元素是其父元素内的第一个子元素”。这并不意味着“该元素是其父元素中的第一个子元素匹配其他条件”。

虽然有 :first-of-type 伪类,但没有 :first-of-class 伪类。 CSS 不直接支持你想要实现的目标。

你可以接近它,它支持你想设置的特定属性,用 general sibling combinator .

.p2 { font-style: italic; }
.p2 ~ .p2 { font-style: normal; }

您将所有匹配元素设置为斜体,然后将后续元素设置为非斜体。

关于html - CSS:定位每个类的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43806504/

相关文章:

html - 将右侧css中的两个图像与单独的行对齐

css - 如何仅在手机或平板电脑 View 上显示菜单?

javascript - 我如何制作具有 3 种颜色和很多曲线的多渐变背景?

html - polymer 纸工具栏忽略正文边距

css - MaterializeCSS 表单在导航栏上可见

html - 溢出 : hidden conundrum on mobile devices

javascript - 在两列上传播 D3.js 图例

html - 有人可以解释一下 HTML5 中的 contextmenu 属性的作用吗?

html - 无法将div移动到底部

jquery - 使输入字段在 bootstrap 3 中内联