首页 > 解决方案 > 标签颜色不变

问题描述

我认为我的代码是正确的,但是在焦点上输入时标签颜色不会改变。请让我知道为什么会这样。

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

解决方案


这目前不起作用的原因与您的 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>


推荐阅读