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.
You can use the CSS 'starts with' attribute selector ( ^= ) to select all labels with a for attribute that starts with 'red', 'green', etc. Show activity on this post. Show activity on this post. For one, you don't have to repeat the color and font-weight styles from the first input[type="checkbox"]:checked + label .
you can disable via css: pointer-events: none; Doesn't work everywhere though. Text input can still be tabbed into.
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.
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.
Then for the fun bit: use CSS to position the labels for text inputs on the left hand side!
input:disabled { background: #dddddd; } input:disabled+label { color: #ccc; } input[type=text]+label { float: left; }
<input type="checkbox" disabled="disabled" id="check1"> <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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With