How to select first label within div using css?

时间:2019-03-06 11:33:45

标签: html css

Hi i want to select first label element within div with classname form_fields.

Below is the code,

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

What i have tried?

.fields label:first-child {
    margin: 20px;
}

But this doesnt apply to the first label inside div of class form_fields. How can i do it? thanks.

5 个答案:

答案 0 :(得分:2)

Try with first-of-type pseudo-selector:

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

答案 1 :(得分:1)

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

答案 2 :(得分: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>

答案 3 :(得分:1)

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

  • const input = `> some text user <b>typed</b> another line another line 2 > another line 3`; const output = input.replace(/^(?!>)(?=[^\n]*\S)/gm, '> '); console.log(output); CSS伪类表示一组兄弟元素中其类型的第一个元素。 See doc
  • VpnService CSS伪类根据其在一组同级兄弟中的位置来匹配给定类型的元素。 See doc

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

enter image description here

:nth-of-type(1)
:first-of-type

答案 4 :(得分:0)

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