css - 标签颜色不变
问题描述
我认为我的代码是正确的,但是在焦点上输入时标签颜色不会改变。请让我知道为什么会这样。
https://jsfiddle.net/wvs34qhu/
body {
font-family: sans-serif;
}
.field {
position: relative;
max-width: 250px;
}
label {
box-sizing: border-box;
display: block;
font-size: .8125em;
padding: .75em 12px;
pointer-events: none;
position: absolute;
text-overflow: ellipsis;
top: 0;
text-align: left;
user-select: none;
white-space: nowrap;
width: 100%;
z-index: 1;
}
input {
background-color: #f5f5f5;
border:0;
border-bottom:2px solid grey;
font-size: 1.3125em;
outline:0;
padding-top:24px;
padding-left:12px;
padding-bottom:2px;
width: 100%;
}
input:focus + label{
color:red;
}
input:focus {
border-bottom:2px solid red;
}
<div class="field">
<label for="input-name">Email address</label>
<input id="input-name" type="name" />
</div>
提前致谢!
解决方案
这目前不起作用的原因与您的 CSS 选择器有关:
input:focus + label
这明确指出,在 HTML 中, thelabel
直接位于 the 之后input
(它不是)。
为了让它工作,因为你已经绝对定位了你的标签,你可以在你的 HTML 中切换它们:
<div class="field">
<input id="input-name" type="name" />
<label for="input-name">Email address</label>
</div>
选择器现在将按预期工作。请参阅以下代码段:
body {
font-family: sans-serif;
}
.field {
position: relative;
max-width: 250px;
}
label {
box-sizing: border-box;
display: block;
font-size: .8125em;
padding: .75em 12px;
pointer-events: none;
position: absolute;
text-overflow: ellipsis;
top: 0;
text-align: left;
user-select: none;
white-space: nowrap;
width: 100%;
z-index: 1;
}
input {
background-color: #f5f5f5;
border:0;
border-bottom:2px solid grey;
font-size: 1.3125em;
outline:0;
padding-top:24px;
padding-left:12px;
padding-bottom:2px;
width: 100%;
}
input:focus + label{
color:red;
}
input:focus {
border-bottom:2px solid red;
}
<div class="field">
<input id="input-name" type="name" />
<label for="input-name">Email address</label>
</div>
推荐阅读
- javascript - "Module not found: can't resolve..." with React app
- node.js - 在没有多部分中间件的情况下正确解析 node/express 中的 FormData 文件?
- html - 水平对齐图像时如何使图像之间的空间为零?
- python - 在pycharm上导入cv2
- c# - 如何将布尔正文发送到 HttpClient.PutAsync 或 HttpClient.PostAsync?
- r - 如何计算多列之间的成对差异?
- mysql - 如何减少被扫描的行数?
- c# - GetEnumerator movenext System.NullReferenceException
- python - 用于自动完成/热键输入的 Pynput 监听器
- javascript - 如何无限次重复 React 元素?