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

如何仅为指定的第一个span元素应用CSS样式?

问题解决:仅为指定第一个span元素应用CSS样式

你尝试为.content容器内的第一个<span>元素(包含Lorem ipsom的那个)设置红色、加粗、12px的字体样式,但原有CSS未生效。

你的原有CSS代码:

.content>span:first-child{
  color: red;
  font-size: 12px;
  font-weight: bold;
}

对应的HTML结构:

<span class="content">
       <svg xmlns="http://www.w3.org/2000/svg">
       <use xlink:href="assets/icons.svg#back-button"></use>
    </svg>
     <span> Lorem ipsom </span>
<!-- 仅该span的字体颜色应为红色 -->

<span>
       <span> </span>
</span>
</span>

问题原因

.content>span:first-child选择器的逻辑是选中.content的第一个子元素,且该元素必须是span。但你的HTML里,.content的第一个子元素是<svg>,并非<span>,所以这个选择器无法匹配到目标元素。

解决方案

使用:first-of-type选择器,它会匹配父元素下同类型元素中的第一个,不受前面其他类型元素的影响。修改后的CSS如下:

.content>span:first-of-type{
  color: red;
  font-size: 12px;
  font-weight: bold;
}

你也可以用:nth-of-type(1)达到完全相同的效果:

.content>span:nth-of-type(1){
  color: red;
  font-size: 12px;
  font-weight: bold;
}

内容的提问来源于stack exchange,提问作者EMahan K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:36:31