vdegenne
vdegenne

Reputation: 13270

how to change css style of an html element only if specified sibling exists?

I browsed into the MDN CSS documentation but I don't see any Combinators that can select the element I want to style.

/* second-span red when first-span is present */
[first-span] ~ [second-span] {
  color: red;
}

/* first-span blue ONLY when second-span is present */
/* HOW TO ? */
[first-span] /* combinator doesn't exist */ {
  color: blue;
}
<p>
  <span first-span="">I am #1</span><br>
  <span second-span="">I am #2</span>
</p>

<p>
  <span first-span="">I am #1</span>
  <!-- no second span -->
</p>

<p>
  <span second-span="">I am #2</span>
</p>

I try to apply a style to an element ONLY if another specified sibling is found among below siblings.

In the snippet, the first CSS statement is used to style an element if the left hand in the selection expression is found among above siblings. But it seems like there is not combinator to have the opposite effect.

How can I do that ?

Upvotes: 2

Views: 426

Answers (2)

wahwahwah
wahwahwah

Reputation: 3177

Through combining nth-child with other pseudo classes it enables you to specify elements from sets of elements with specific lengths.

This is complicated slightly by your use of the <br> tag, as its a child element of <p>, however, this should still work for your needs:

/* this will color the first element of three children nested in a p tag blue */
p span:nth-child(1):nth-last-child(3){
  color: blue;
}

/* this will color the third element of three children nested in a p tag red */
p span:nth-child(3):nth-last-child(1) {
    color: red;
}
<p>
  <span first-span="">I am #1</span><br>
  <span second-span="">I am #2</span>
</p>

<p>
  <span first-span="">I am #1</span>
  <!-- no second span -->
</p>

<p>
  <span second-span="">I am #2</span>
</p>

This targets the first of three elements, then the last of three.

Upvotes: 1

Mr. Hugo
Mr. Hugo

Reputation: 12592

You can use jQuery (to keep things clean), like this:

if($('p > span:nth-of-type(2)').length) {
   $('p > span:nth-of-type(1)').css('color','red');
}

Check if element exists in jQuery

Upvotes: 0

Related Questions