Show label when you tab to new field

  • Profile Image
    Asked on March 23, 2016 at 05:02 PM

    My form is designed so that when you move your mouse over a field, everything else fades out to 0.5 opacity. This works brilliantly. But when I'm in the form and I tab to the next field, that input field's opacity is back to 1 as intended. But the label stays at 0.5. 

    Here's the CSS I have so far: 

    /* How to fade out content */

    ul:hover li {

        opacity : 0.5;



    ul:hover li:hover {

        opacity : 1;



    Any suggestions? I found a CodePen which appears to do what I want, but they're using LESS.

  • Profile Image
    Answered on March 23, 2016 at 06:48 PM

    The exact behavior depicted in that CodePen can't usually be achieved on the structure such as that of our forms, because CSS can't affect parent elements based on what is going on inside its children elements.

    In that CodePen example, they are using an overly simplistic model where the input element is placed just before the label element, and they are siblings. This is the only structure where such CSS could work:

    > question container
    >> input-field
    >> label-for-input-field

    As both the input and label elements are on the same level (they are siblings) and input field is before the label, the label can see the :focus state in their example:

    > question container
    >> input-field:focus
    >> label-for-input-field

    This allows them to use CSS such as:

    input-field:focus ~ label-for-input-field {
        opacity: 1;

    On our forms, the structure of the form is much more complex, and the label and input fields are neither on the same level, nor is the input field before the label. This makes it impossible to style labels based on focus state on the input fields, with pure CSS alone.

    Here is a general structure of our simple form fields, which differs on more complex fields:

    > question container
    >> label-for-input-field
    container of input fields

    >>> input-field

    The reason we have another container after the label is because we can have multiple input fields there, such as "first name" and "last name". As you can see, in the above structure, the label is (1) before the input element and (2) on a parent level, which makes it not possible to target by CSS.

    Luckily, we have implemented a JavaScript workaround on our forms, so we add a .form-line-active class to the main question container whenever an input field inside of it has focus. This allows us to use CSS such as this:

    .form-line-active {
        opacity : 1 !important;

    Simple, don't you think? :)

    Please try it out, and let us know if it works to your satisfaction.