2

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 ?

vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • You can do one or the other, like you have currently or using flexbox with the `order` property to re-organize the elements so the adjacent/general sibling selector will work, but you can't do both with just CSS. CSS can only select elements that come after or are nested inside an element - it can't go back up in the DOM. I think you'll need javascript if you want to be able to handle both cases – Michael Coker Jul 20 '17 at 17:09
  • Like this https://codepen.io/mcoker/pen/JJgOOP – Michael Coker Jul 20 '17 at 17:12

2 Answers2

1

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.

wahwahwah
  • 3,254
  • 1
  • 21
  • 40
0

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

Mr. Hugo
  • 11,887
  • 3
  • 42
  • 60