Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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, but it doesn't:

fieldset {background: #ffe;}
input[type=text]:focus+fieldset {background: #ff0;}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>
  <legend>Fieldset 1</legend>
  <input name="text1" type="text" />
  <input name="text2" type="text" />
  <div></div>
</fieldset>
<fieldset>
  <legend>Fieldset 2</legend>
  <input name="text3" type="text" />
  <input name="text4" type="text" />
  <div></div>
</fieldset>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...