Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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',function(){
        $('label[for='+$(this).attr('id')+']').addClass('active');
    });
    $(document).on('blur', 'input',function(){
        $('label[for='+$(this).attr('id')+']').removeClass('active');
    });

HTML:

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

And CSS:

.active{ color:red; }

Edit: I am surely aware of the child and sibling selectors "workarounds", but rearranging clean markup for the pure sake of styling seems not right, so if there is another pure css way this answer wins!

http://jsfiddle.net/fchWj/3/

like image 336
worenga Avatar asked May 31 '13 14:05

worenga


People also ask

How do I style a label and input in CSS?

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.


1 Answers

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

Html

<div class="row">
    <input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
    <label for="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 +.

like image 109
PSL Avatar answered Sep 17 '22 12:09

PSL