如何使用CSS选择第一个div标签内的标签?

3

嗨,我想选择class为form_fields的div中的第一个label元素。

以下是代码:

 <form>
     <div className="form_fields">
         <span>first span</span>
         <div>first div</div>
         <label>
             <span>Name</span>
         </label>
         <label>Description</label>
     </div></form>

"最初的回答"
我尝试了什么?
.fields label:first-child {
    margin: 20px;
}

但是这不适用于类为form_fields的div内的第一个标签。我该怎么办?谢谢。最初的回答。

在内联HTML中不能使用className,应该使用class。同时确保class与CSS中使用的class相同。:first-child选择label的第一个子元素。请参考下面的答案以获得正确的方法。 - Mark Baijens
我认为这是对label元素的误用...你应该首先修复HTML(如果有这个选项的话)。 - 04FS
5个回答

4

尝试使用first-of-type伪类选择器:

.form_fields label:first-of-type {
    margin: 20px;
}

1

您可以在2个伪类之间进行选择:

  • :first-of-type CSS 伪类表示一组兄弟元素中其类型的第一个元素。查看文档
  • :nth-of-type(1) CSS 伪类基于它们在一组同级元素中的位置,匹配给定类型的元素。查看文档

使用 :first-of-type 的解决方案:

enter image description here

.form_fields label:first-of-type {
  background:red;
}
<form>
  <div class="form_fields">
    <span>first span</span>
    <div>first div</div>
    <label>
      <span>Name</span>
    </label>
    <label>Description</label>
  </div>
</form>


1
.form_fields label:nth-of-type(1) {
    margin: 20px;
}

1

我可以想象你想做更多的事情,但在这里询问是一个很好的开始。在HTML和CSS中,有几种方法可以实现相同的结果,你选择的路径通常基于个人喜好。在这个特定的情况下,你只是有一些概念上的错误,但你肯定在正确的轨道上。

  1. 在你的标签中,应该将className更改为"class"。
  2. 在你的样式中,将:first-child更改为:first-of-type
<form>
  <div class="form_fields">
    <span>first span</span>
    <div>first div</div>
    <label>
      <span>Name</span>
    </label>
    <label>Description</label>
  </div>
</form>

<style>
  .form_fields label:first-of-type {
    margin: 20px;
  }
</style>


0

.form_fields label:nth-of-type(1) {
     color: blue;
 }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接