Is it possible to change a fieldset's background-color on input:focus?

前端 未结 5 575
刺人心
刺人心 2020-12-20 23:04

Is it possible to have the background-color of a form\'s fieldset change when the cursor is inside any of that fieldset\'s text fields?

I assumed this might work, b

5条回答
  •  感动是毒
    2020-12-20 23:53

    You can't style a fieldset based on the focus state of one of its children inputs.

    However, you can simulate the effect by adding an empty div as the last child of the fieldset, and styling it. This div's styles can then be changed using the general sibling selector on the focused input:

    fieldset {
      border: none;
      position: relative;
      margin-bottom: 0.5em;
    }
    
    legend {
      position: relative;
      background: white;
    }
    
    input:focus {
      background: lightyellow;
    }
    
    input:focus ~ div {
      border: 2px solid black;
      background: #def;
    }
    
    fieldset > div {
      height: calc(100% - 0.5em);
      width: 100%;
      position: absolute;
      top: 0.5em;
      left: 0;
      border: 2px solid lightgray;
      z-index: -1;
    }
    Fieldset 1
    Fieldset 2

提交回复
热议问题