Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a HTML label for disabled input

Tags:

html

css

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.

like image 683
mjr Avatar asked Oct 14 '13 14:10

mjr


People also ask

How do you change the style of a label in HTML?

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 .

How do I make input disabled in CSS?

you can disable via css: pointer-events: none; Doesn't work everywhere though. Text input can still be tabbed into.

How do you style inputs and labels?

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

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>
like image 189
gvee Avatar answered Oct 19 '22 15:10

gvee