0

I would like to target the previous sibling with css. The following article suggests it can be done. Article on how to select the previous sibling in css (https://tobiasahlin.com/blog/previous-sibling-css-has/)

However, it just won't work. Even on my code below.

.c-floating-label:has(+ .c-input) {
    color:blue;
}

h2:has(+ p) {
  color:blue;
}


.box:has(+ .circle) {
    background:blue;
}
<label for="fullName" class="c-floating-label">Full name</label>
<input type="text" name="fullName" id="fullName" placeholder="Full name" class="c-input">

<br/>

<h2>I am a heading</h2>
<p>I am a paragraph</p>

<br/>

<div class="box">Box</div>
<div class="circle">Circle</div>
<div class="box">Box</div>
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
Al-76
  • 1,738
  • 6
  • 22
  • 40
  • 2
    I converted your code into a snippet so it can be run inside your question. What exactly is not working that you want to change? I see lots of stuff being colored blue so I'm not clear on what you want to be different than how it is currently working – Chris Barr Jul 20 '23 at 13:26
  • Calling it a previous selector is a little misleading, it is only ever "looking" forwards, but it appears to do what it's intended to. – DBS Jul 20 '23 at 13:30
  • Note the top answers on the duplicate target, which state this does not work in Firefox. Given that your code works correctly in Chrome, Edge, Opera, etc. I can only assume you are testing in Firefox (or some wildly out-of-date version of one of the prior browsers). – TylerH Jul 20 '23 at 13:30
  • It’s all working fine for me, assuming your CSS is describing correctly what you want. Note that it won’t work on Firefox unless the user has set a flag in the browser. What output are you seeing and on what browser? – A Haworth Jul 20 '23 at 13:30
  • @ChrisBarr Thanks Chris! That helps. You are right, the text is blue as it should be. However, this doesnt render in my project or on codepen in the same way https://codepen.io/Al-76/pen/PoxaOBb Eg there's no blue. I wonder what can be happening? – Al-76 Jul 20 '23 at 13:31
  • Your codepen looks identical to the snippet for me. – DBS Jul 20 '23 at 13:31
  • Ah it seems its a Firefox issue! – Al-76 Jul 20 '23 at 13:32
  • @AHaworth Firefox issue. Need to find a workaround :( – Al-76 Jul 20 '23 at 13:37
  • https://stackoverflow.com/questions/73936048/how-do-you-enable-has-selector-on-firefox – Wimanicesir Jul 20 '23 at 13:39

0 Answers0