Home > Net >  How to apply styles to label while input:focus is true
How to apply styles to label while input:focus is true

Time:09-08

<div >
    <label>Input Label</label>
    <input />
</div>

This is the html, I want to resize and reposition the label test when the input focus is active

my css looks something like this

.input-container > input:focus .input-container > label {
    color: green;

}

For this example, is there a way to change the label text color to green when the input is focussed? Thank you, I know this is easy with JS, I am looking for an all css solution though

CodePudding user response:

I think something like this would work:

.label {
  color: blue;
}

.input-container:focus-within .label {
  color: green;
}
<div >
  <label >Input Label</label>
  <input  />
</div>

(this allows you to change the color of the label element whenever the focus is on any of the .input-container child elements)

CodePudding user response:

As per the comments:

"A CSS rule can only affect sibling elements after the current element. So you would need the input to be before the label in the markup to be able to do this"

So you will have to put the input first. Then you can use flex with row-reverse on .input-container to re-adjust the order. Then just use the sibling selector ~ to style the label when input:focus.

.input-container {
  display: flex;
  flex-flow: row-reverse;
  justify-content: start;
}

input {
  margin-left: .5em;
}

.input-container > input:focus ~ label {
    color: green;
}
<div >
  <input>
  <label>Input Label</label>
</div>

CodePudding user response:

If you can change the order of the markup, you can use the sibling selector ( ) Documentation

.input-container > input:focus   label {
  color: green;
}
<div >
  <input />
  <label>Input Label</label>
</div>

You can use CSS to position the label/input differently (visually), as long as the markup remains the same.

  • Related