I wonder if this is even 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 I can do:
label:first-child{}
but I wonder if it is possible to select only the first label preceded by a h1 that is not at the same level with + or ~ or something else.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
The CSS adjacent sibling selector is used to select the adjacent sibling of an element. It is used to select only those elements which immediately follow the first selector.
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
No, there is no "previous sibling" selector. On a related note, ~ is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector. + is for next sibling and is CSS2.
You can use the below selector:
h1 + form > label:first-child {
/* some properties here */
}
So the above selector will select the form
element which is a sibling of h1
and than it gets in and selects the first direct label
element and hence am using >
You can safely get rid of the >
if you are sure that you might not have any further nested label
elements inside your form
element.
Note that this is a very generic tag selector, I will suggest you to wrap your elements inside a wrapper element and give it a class
say form-wrapper
and modify your selector like
.form-wrapper h1 + form > label:first-child {
/* some stuff */
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With