0

I want the effect of coloring label on input focus. Like when i focus input box, the label color should change to blue. But this is not working and I want to know why as well as how to fix this?

.test-label{
			color: purple;
}
.test-box:focus .test-label{
			color: blue !important;
}
<form>
		<label class = "test-label">Label</label>
		<br />
		<input type = "text" class = "test-box">
	</form>

1
  • two selectors separated by space means they would be nested, but your label and input are not nested. Commented Oct 12, 2017 at 15:57

5 Answers 5

2

You can use focus-within for this.

Note it has limited support.

.test-label {
  color: purple;
}

form:focus-within .test-label {
  color: blue;
}
<form>
  <label class="test-label">Label</label>
  <br />
  <input type="text" class="test-box">
</form>

Sign up to request clarification or add additional context in comments.

Comments

2

Move your input inside the label and use :focus-within (note: doesn't currently work in IE or Edge browsers)

.test-label {
  color: purple;
}

.test-label:focus-within {
  color: blue;
}
<form>
  <label class="test-label">Label
        <br />
        <input type="text" class="test-box">
  </label>
</form>

Comments

1

Just keep label after input and apply General Sibling Selector, and make label position:absolute to keep label position on top

.myInput:focus~label {
  color: blue !important;
  cursor: pointer;
}

.test-label {
  color: purple;
  position: absolute;
  top: 0;
  left: 0;
}

.test-box {
  position: relative;
}

.myInput:focus~label {
  color: blue !important;
  cursor: pointer;
}

.myInput:hover {
  color: blue !important;
  cursor: pointer;
}
<form class="test-box">

  <br />
  <input type="text" class="myInput">
  <label class="test-label">Label</label>
</form>

and this will run on all modern browsers. Hope this will help you.

1 Comment

No Problem, Tricky thing is always better ;)
0

.test-label{
			color: purple;
}
.test-box:hover .test-label{
			color: blue !important;
            cursor: pointer;
}
<form class="test-box">
		<label class = "test-label">Label</label>
		<br />
		<input type = "text">
	</form>

1 Comment

I want on focus dude.
0

Remove the extra selector from ".test-box:focus" .

.test-label{
			color: purple;
}
.test-box:focus {
			background-color: blue !important;
}
<form>
		<label class = "test-label">Label</label>
		<br />
		<input type = "text" class = "test-box">
	</form>

1 Comment

No i want text color to be changed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.