8

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
  • 6,811
  • 9
  • 36
  • 59

2 Answers2

10

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
  • 249,902
  • 55
  • 405
  • 483
8

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
  • 81,773
  • 12
  • 93
  • 144