-1

enter image description here

For the code above, I want apply the CSS property of "stroke: green" for the SVG element ONLY when div.pointer-events-none has an adjacent sibling of input:focus-within.

.pointer-events-none + input:focus-within {
    svg {
        stroke: green;
    }
}
div.text-field {
    div.relative {
        div.pointer-events-none + input:focus-within ~ svg {
            stroke: green;
        }
    }
}

I'm not being able to target the SVG inside div.pointer-events-none :/

makazoid
  • 29
  • 6
  • [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – CBroe Jul 25 '23 at 08:35
  • Your first attempt would select the `svg` element if it was a _descendant_ of the `input` field (which it isn't, and of course can't be), and your second one would select the svg, if it was a following sibling of the input, which is also not the case. – CBroe Jul 25 '23 at 08:38
  • I don't think you will be able to achieve this any other way than with `:has()`, on the level of the parent with the `relative` class - you need to select that element first, if it has the combination of `.pointer-events-none` followed by the focussed input; and if it does, then you can select the svg inside of it. (Only, `:has()` has no support in Firefox yet, unless the user explicitly enables it.) – CBroe Jul 25 '23 at 08:39
  • 1
    Looks like the SVG is only visual sugar here, and has no semantic meaning, or purpose of transporting any actual information(?) - so the DOM order of the div and the input field could probably be reversed, and the visual order reversed again via flexbox. _Then_ the div with the svg could be selected based on being a sibling following the focussed input element. – CBroe Jul 25 '23 at 08:50
  • I changed the DOM order and now it worked! Thanks @CBroe – makazoid Jul 25 '23 at 09:21

1 Answers1

1

Your first selector tries to target an svg inside the input.

Your second selector tries to target an svg that is a later sibling of the input.

There isn't a pure CSS approach to this that I consider supported enough for production use (unless the effect is only "nice to have"). The :has psuedo-class can do it, but lacks support in Firefox at present.

.foo span { background: yellow; }
.foo:has(+ input:focus-within) span { background: blue; }
<div class="foo">
    <span>Hello</span>
</div>
<input>

A JavaScript approach would be better supported:

const input = document.querySelector('input');
const div = document.querySelector('.foo');
input.addEventListener('focus', event => div.classList.add('focused-input-follows'));
input.addEventListener('blur', event => div.classList.remove('focused-input-follows'));
.foo span { background: yellow; }
.foo.focused-input-follows span { background: blue; }
<div class="foo">
    <span>Hello</span>
</div>
<input>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335