Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...