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>

6
  • 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. Commented Jun 6, 2017 at 14:23
  • Possible duplicate - stackoverflow.com/questions/1817792/… Commented Jun 6, 2017 at 14:24
  • Make <label> red with no <div> before it, but after it. Commented Jun 6, 2017 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. Commented Jun 6, 2017 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. Commented Jun 6, 2017 at 14:29

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

As demonstrated in your snippet, this still matches both labels.
Your answer is accepted so I guess I misunderstood the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.