user3108268
user3108268

Reputation: 1083

Apply CSS ~ combinator for first child

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>

Upvotes: 0

Views: 104

Answers (1)

Johannes
Johannes

Reputation: 67778

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>

Upvotes: 1

Related Questions