You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为HTML嵌套结构中首个出现的<p>元素首字母设置样式?

问题:为HTML中首个出现的

元素首字母设置样式

需求:需要为HTML嵌套结构里第一个出现的

元素的首字母设置样式,HTML结构不固定,首个

可能出现在任意

中,希望通过CSS实现,且不想使用类或ID(避免客户在WordPress Elementor中手动添加),尝试使用:has()选择器但未成功。

HTML示例结构

eg: 1

<body>
  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 1</p>
    <img src="" alt="" />
    <p>//something 2</p>
    <p>//something 3</p>
  </section>

  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 4</p>
    <p>//something 5</p>
  </section>
</body>

eg: 2

<body>
  <section>
    <p>//something 1</p>
    <img src="" alt="" />
    <p>//something 2</p>
    <p>//something 3</p>
  </section>

  <section>
    <img src="" alt="" />
  </section>

  <section>
    <p>//something 4</p>
    <p>//something 5</p>
  </section>
</body>

尝试过的CSS方案(均未达到预期)

三种方案都会同时选中<p>//something 1</p>和<p>//something 4</p>的首字母,无法仅选中目标元素:

1st 方案

section:has(p):first-of-type p:first-of-type::first-letter{
  background: red;
}

2nd 方案

section:has(p):first-child p::first-letter{
 background:red;
}

3rd 方案

p:first-child::first-letter{
 background:red;
}

疑问

想了解这类复杂CSS选择器是否存在性能损耗,以便决定是否制作自定义部件。


内容的提问来源于stack exchange,提问作者vishnu p s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 17:03:29