Drupal input label accessibility issue

There is one particular issue with drupal forms regarding accessibility compliance that comes up all the time.

The designs ask for no label on the form input, so back end developers leave it off in the form api. However this is very bad practice from the point of accessibility. Since a screen reader does not know what information should go into the input field.

The solution is to always create labels for form input fields but hide them with special CSS rules.

Here it is:

1. Update the form input so it has  a label.

2. Wrap the input together with the label in a div with a special CSS class.

// FORM LABEL 
$form['search']['keyword'] = array(
    '#type' => 'textfield',
    '#description' => "Enter your address or assessor's parcel number.",
    '#size' => 20,
    '#title' => 'Property Information', // <------------ ADD THIS
    '#maxlength' => 100,
    '#required' => TRUE,
    '#default_value' => !empty($form_state['values']['keyword']) ? $form_state['values']['keyword'] : '',
    '#prefix' => '<div class="hidden-label-inside">', // <------------ ADD THIS
    '#suffix' => '</div>' // <------------ ADD THIS
);

3. Add special CSS rules to hide the label from the screen but leave it there for screen readers.

.hidden-label-inside label {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0,0,0,0);
    border: 0;
}

3.1 If you are using the Bootstrap 3.3.7 framework this can be achieved by using the .sr-only class as a mixin in your theme like so. In case you don’t need the CSS cod above

.hidden-label-inside {
  label {
    .sr-only;
  }
}

I hope this helps.

Cheers, Lehel