htmlcsscss-selectorsvisibility

Is focus change in HTML instant for CSS purposes?


I have a pair of inputs, where the second input is like a "dropdown": it should only appear when the first input is focused, and then it should be focusable and editable until the focus moves away from the inputs completely.

I tried to implement this using CSS :focus selectors.

input.conditional {
  display: none;
}

input.conditional:focus {
  display: block;
}

input.main:focus~input.conditional {
  display: block;
}
<input type="text" class="main" placeholder="main">
<input type="text" class="conditional" placeholder="conditional">

However, when I focus on the first input, and then try to click on (or TAB into) the second input, it immediately disappears. It looks as if it becomes display: none and unfocusable before it can receive focus.

I tried intercepting the focus/blur events, and even though blur properly has the second input as relatedTarget, there is no follow-up focus event for the second input.

Is there supposed to be a "gap" in focus transition, where the first input no longer has :focus, but the second input doesn't have :focus yet?


Solution

  • I am seeing different effects on different browsers.

    Edge/Chrome on Windows11 gives the behavior you describe - the conditional input disappears when focus is removed from main.

    However, on Safari IOS it gives the behavior you want - conditional remains visible.

    To achieve the desired behavior consistently you could put the two inputs in a container and sense focus within that rather than on the two inputs separately.

    <style>
      input.conditional {
        display: none;
      }
      
      .container:focus-within .conditional {
        display: block;
      }
    </style>
    <div class="container">
      <input type="text" class="main" placeholder="main">
      <input type="text" class="conditional" placeholder="conditional">
    </div>