Vandervals
Vandervals

Reputation: 6064

CSS selector for the first element after another not being siblings

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.

Upvotes: 5

Views: 728

Answers (3)

m4n0
m4n0

Reputation: 32355

You can access the next sibling using + and then use the descendent selector to target the label.

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>

Upvotes: 1

stevenw00
stevenw00

Reputation: 1156

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>

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157414

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 */
}

Upvotes: 6

Related Questions