0

I have two items in a parent and need to apply CSS to first child only if second/other child exist. ~ does that, buy only to siblings of the first child and I need it vice versa.

tldr: Make <label> red with no <div> before it, but after it

div ~ label {
  color: red;
}

https://jsfiddle.net/q836Lev1/1/

div ~ label {
  color: red;
}
<fieldset>
  <div></div>
  <label>this label is red</label>
  <div>works, but not good, there must be no first div.</div>
</fieldset>

<fieldset>
  <label>this label is red</label>
  <div>doesn't work, label should be red and div comes after.</div>
</fieldset>
Johannes
  • 64,305
  • 18
  • 73
  • 130
user3108268
  • 1,043
  • 3
  • 18
  • 37
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Paulie_D Jun 06 '17 at 14:23
  • Possible duplicate - https://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-css-selector – Paulie_D Jun 06 '17 at 14:24
  • Make ` – user3108268 Jun 06 '17 at 14:24
  • You could wrap the `div` and `label` in another `div` and use `label:first-child:last-child`. If there's no nested `div`, it'll select the `label`. – Joseph Marikle Jun 06 '17 at 14:28
  • From the CSS3 standard: The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one. So it doesn't work the way you want. – Gerard Jun 06 '17 at 14:29
  • The ~ combinator is probably a red herring here. Is it important that the first non-label child is a div? If not, you can get away with label:first-child. Is it important that the label have a following sibling? Then this is a duplicate of [CSS select first child only if two children](https://stackoverflow.com/questions/18431662/css-select-first-child-only-if-two-children) instead. No need to complicate things. – BoltClock Jun 06 '17 at 14:38

1 Answers1

1

You could use label:nth-last-child(2):

label:nth-last-child(2) {
  color: red;
}
<fieldset>
  <div></div>
  <label>this label is red</label>
  <div>works, but not good, there must be no first div.</div>
</fieldset>

<fieldset>
  <label>this label is red</label>
  <div>doesn't work, label should be red and div comes after.</div>
</fieldset>
Johannes
  • 64,305
  • 18
  • 73
  • 130