使用 CSS 更改带有嵌套输入字段的字段集的背景颜色

Changing a Fieldset's Background Color with Nested Input Fields using CSS

我正在使用这个解决方案: Is it possible to change a fieldset's background-color on input:focus?

... 在用户浏览表单时更改字段集的背景。在基本层面上,这很好用。在更高级的层面上,我无法在嵌套在条件 div 内的输入字段上进行这项工作。换句话说,在他的示例中,输入不再是 div 的兄弟。

给你一个视觉效果,这个有效:

<fieldset>
<input>
<div></div>
</fieldset>

但这不是:

<fieldset> 
<div class="conditional"> 
<input> 
</div> 
<div></div> 
</fieldset>

实际上,您现在可以影响焦点输入的父级

:focus-within

The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.)

MDN

fieldset:focus-within {
  background: red;
}
<fieldset>
  <input>
</fieldset>