CSS selector for the first element after another non-sibling

I wonder if this is possible. With this html:

<h1></h1> <form> <label><input type="text"></label> <label><input type="text"></label> <label><input type="text"></label> </form> 

I know that I can:

 label:first-child{} 

but I am wondering if it is possible to select only the first shortcut, which is preceded by h1, which is not at the same level as + or ~ or something else.

+5
source share
3 answers

You can use the selector below:

 h1 + form > label:first-child { /* some properties here */ } 

So the above selector will select the form element, which is a child of h1 , and then it gets up and selects the first straight label element, and so I use >

You can safely get rid of > if you are sure that you may not have nested label elements inside your form element.


Note that this is a very general tag selector, I suggest you wrap the elements in a shell element and give it a class say form-wrapper and change your selector, for example

 .form-wrapper h1 + form > label:first-child { /* some stuff */ } 
+6
source

 h1 + form label:first-child { color: red; } 
 <h1>H1</h1> <form> <label>First</label> <label>Second</label> <label>Third</label> </form> <h2>H2</h2> <form> <label>First</label> <label>Second</label> <label>Third</label> </form> 
+1
source

You can access the next sibling with + , and then use the descendant selector to target the tag.

 h1 + form label:first-child { padding-right: 120px; } 
 <h1></h1> <form> <label> <input type="text"> </label> <label> <input type="text"> </label> <label> <input type="text"> </label> </form> 
+1
source

All Articles