Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

css - 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.

question from:https://stackoverflow.com/questions/19362716/how-to-style-a-html-label-for-disabled-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...