mjr mjr - 7 days ago 5
CSS Question

How to style a HTML label for disabled input

I would like the labels for my form elements to be greyed out if the input is disabled and am not able to get it to work for text inputs. I have tried the following:

input:disabled {
background:#dddddd;
}

input:disabled+label{color:#ccc;}

<input type='checkbox' disabled id='check1'>
<label for='check1'>Check</label>
<br>
<label for='text1'>Text</label>
<input type='text' id='text1' disabled>


Js Fiddle

The styling works for the checkbox label, but not the text label. Are checkboxes the only input types that let you style their labels via css?

I testing with Firefox.

Answer

Based on the comment made by @andi:

input:disabled+label means that the label is immediately AFTER the input. In your HTML, the label comes BEFORE the text input. (but there's no CSS for "before".)

He's absolutely right. But that shouldn't stop us being able to solve the problem with a little trickery!

First step: swap the HTML elements order so that the <label> appears after the <input>. This will allow the styling rules to work as desired.

HTML

<input type="checkbox" id="check1" disabled="disabled">
<label for="check1">Check</label>
<br>
<input type="text" id="text1" disabled="disabled">
<label for="text1">Text</label>
<br>
<input type="checkbox" id="check2">
<label for="check2">Check</label>
<br>
<input type="text" id="text2">
<label for="text2">Text</label>

Now the fun bit: use CSS to position the labels for text inputs on the left hand side:

CSS

input[type=text]+label {
    float: left;
}

DEMO: http://jsfiddle.net/F2Nh4/5/