Skip to content Skip to sidebar Skip to footer

Toggling Styles On Label (active/focus) For Input Field With Css Only

Wondering whether if there is a css-only way to perform to toggle styles on the corresponding label on input's focus. So far I have: $(document).on('focus active', 'input',func

Solution 1:

Try this way:- Place your label after input and float it left. And apply siblings.

Html

<div class="row">
    <inputid="contact_form_mail"name="contact_form_mail"type="email"placeholder="Your e-mail address..."><labelfor="contact_form_mail">Email</label></div>

CSS

label {
    float:left;
}
input:focus + label {
    color:red;
}

Demo

This is a hack to get the adjacent sibling selector work as it applies only on the following element and not the preceding one. ~ will select all the adjascent siblings after this element. So if you are having different .row for each section of inputs then use +.

Solution 2:

If you are willing to switch elements, than here you go

Demo

<div><inputtype="text" /><labelfor="e_mail">E-Mail</label></div>
label {
    float: left;
    margin-right: 5px;
}

input[type=text]:focus + label {
    color: red;
}

Explanation: We are using + adjacent selector here, so when the textbox is focused, we select the label tag and apply color red

Note: Don't forget to clear floats ;)

Solution 3:

It's possible with CSS only, without switching the order of the label and input. You can use a :focus-within CSS pseudo-class on the parent element, which applies to elements, that has a child element with the focus.

In your example, you could use the following:

.row:focus-within label {
    color: red;
}

Note, that this pseudo-class is relatively new, so only modern browsers support it.

Solution 4:

There is, but only if you place the label after the input.

<input name="field"type="text" />
<label for="field">Label Here</label>

input:focus + label{
    color: red;
}

Now if you want the label to be placed before it, then you need to do some css styling with position absolute to place the label before the input field, then add some margin left on the input to move it to the right.

<div><inputname="field"type="text" /><labelfor="field">Label Here</label></div>
div{
   position: relative;
}
input{
   margin-left: 40px;
}
label{
   position:absolute;
   left:0;
}

Solution 5:

This give you label on top of input, highlight label while input focus. HTML

<div class="row">
<inputid="contact_form_mail"name="contact_form_mail"type="email"placeholder="Your e-mail address..."><labelfor="contact_form_mail">Email</label></div><code>
.row{
    display:flex;
    flex-direction:column-reverse;
    align-self:flex-start;
 }
 .row input:focus{
     border: 1px solid red;
  }
  .row input:focus+label{
     color:red;
  }
  </code>

Post a Comment for "Toggling Styles On Label (active/focus) For Input Field With Css Only"