Home > OS >  Change color of legend on input focus
Change color of legend on input focus

Time:11-16

Is there any way with CSS for changing color of legend text when input gets the focus, similar to fieldset working?

Each of the fieldset changes color when their particular input gets the focus. I am trying similarly for legend.

fieldset {
    border-radius: 0.6vh;
    border: 1vh solid black;
    padding: 1.68vh;
}

fieldset:focus-within {
    border-color: blue;
}

/* legend not changing color when focused on input */
legend:focus-within {
    color: blue;
}

legend {
    padding: 0 1.2vh;
    color: black;
}

input {
    border: none;
    padding: 0.29vh;
}

input::placeholder {
    color: black;
}

input:focus {
    outline: none;
}
<fieldset>
  <legend>Name</legend>
  <input type="text" placeholder="Your name">
</fieldset>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to get the event from the input focus and select with > the legend text and change color.

fieldset {
    border-radius: 0.6vh;
    border: 1vh solid black;
    padding: 1.68vh;
}

fieldset:focus-within {
    border-color: blue;
}

/* legend not changing color when focused on input */
fieldset:focus-within > legend {
    color: blue;
}

legend {
    padding: 0 1.2vh;
    color: black;
}

input {
    border: none;
    padding: 0.29vh;
}

input::placeholder {
    color: black;
}

input:focus {
    outline: none;
}
<fieldset>
  <legend>Name</legend>
  <input type="text" placeholder="Your name">
</fieldset>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do it with js function.

    function changeColorText() {
      let x = document.getElementById("text-area");
      x.style.color = "blue";  
    }
  
fieldset {
    border-radius: 0.6vh;
    border: 1vh solid black;
    padding: 1.68vh;
}

fieldset:focus-within {
    border-color: blue;
}

/* legend not changing color when focused on input */
legend:focus-within {
    color: blue;
}

legend {
    padding: 0 1.2vh;
    color: black;
}

input {
    border: none;
    padding: 0.29vh;
}

input::placeholder {
    color: black;
}

input:focus {
    outline: none;
}
<fieldset>
  <legend>Name</legend>
  <input type="text" id="text-area" placeholder="Your name" onfocus="changeColorText()">
</fieldset>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Do you mean that?

  • Related