0
<div class="input-container">
    <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

j08691
  • 204,283
  • 31
  • 260
  • 272
Erik Lew
  • 13
  • 2
  • 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. – DBS Sep 07 '22 at 15:18
  • 1
    yes, you can use the `focus-within` selector. i have created an example for you as an answer – Boguz Sep 07 '22 at 15:28

3 Answers3

4

I think something like this would work:

.label {
  color: blue;
}

.input-container:focus-within .label {
  color: green;
}
<div class="input-container">
  <label class="label">Input Label</label>
  <input class="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)

Boguz
  • 1,600
  • 1
  • 12
  • 25
0

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

.input-container > input:focus + label {
  color: green;
}
<div class="input-container">
  <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.

DBS
  • 9,110
  • 4
  • 35
  • 53
0

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 class="input-container">
  <input>
  <label>Input Label</label>
</div>
Kameron
  • 10,240
  • 4
  • 13
  • 26