Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 574
Vandervals Avatar asked Jul 10 '15 09:07

Vandervals


People also ask

How do you target only the first element in CSS?

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.

Which selector selects only the first adjacent sibling?

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.

What selector to use if we want to select the first child of its parent that is of its type?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How do I target a previous sibling in CSS?

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.


2 Answers

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 */
}
like image 109
Mr. Alien Avatar answered Nov 15 '22 03:11

Mr. Alien


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>
like image 25
stevenw00 Avatar answered Nov 15 '22 03:11

stevenw00