11

In css, can select an element that follows an element using the + operator. For example, I can select only inputs that directly follow labels by doing:

label + input {
    color: red;
}

Is there a way to do the opposite, so like "not adjacent to"? In my example, is there a way to select all inputs that do not directly follow labels?

Edit: It needs to select ALL inputs that don't directly follow labels, including inputs that are in places with no labels whatsoever.

Pete
  • 7,289
  • 10
  • 39
  • 63

2 Answers2

11

I think it would be

input:first-child, :not(label) + input {
  color: red;
}

input {
  background: red;
}
input:first-child, :not(label) + input {
  background: #0f0;
}
body > * {
  display: block;
  width: 100%;
}
<input value="Match (first child)" />
<label>&lt;label&gt;</label>
<span>&lt;span&gt;</span>
<input value="Match (immediately follows a non-label)" />
<label>&lt;label&gt;</label>
<input value="NO match (immediately follows a label)" />
<span>&lt;span&gt;</span>
Oriol
  • 274,082
  • 63
  • 437
  • 513
9

Like this

:not(label) + input {
    color: red;
}

... well, if you will have an input direct after the body tag you need Oriol's additional selector input:first-child

Asons
  • 84,923
  • 12
  • 110
  • 165