如何为禁用的输入设置HTML标签样式 [英] How to style a HTML label for disabled input

查看:97
本文介绍了如何为禁用的输入设置HTML标签样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入被禁用并且无法用于文本输入,我希望表单元素的标签显示为灰色.我尝试了以下方法:

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

样式适用于复选框标签,但不适用于文本标签.复选框是让您通过CSS设置标签样式的唯一输入类型吗?

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?

我正在使用Firefox进行测试.

I testing with Firefox.

推荐答案

基于@andi的评论:

Based on the comment made by @andi:

input:disabled+label表示标签紧随输入之后.在HTML中,标签位于文本输入之前. (但之前"没有CSS.)

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!

第一步:交换HTML元素顺序,以使<label>之后出现在<input>之后.这将使样式规则能够按需工作.

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.

那么有趣的是:使用CSS将文本输入的标签放置在左侧!

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>

这篇关于如何为禁用的输入设置HTML标签样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆