【发布时间】:2021-08-21 16:59:05
【问题描述】:
我正在处理一个现有表单,我想在其中引入浮动标签。
我在堆栈溢出方面看到的许多解决方案都很棒,但需要 label 标签直接位于 <input> 标签下方。 For example here.
在我正在处理的表单上,我的label 标签位于<input> 标签的上方。输入标签位于单独的 div 中。 (我不允许移动这些标签 - 请不要问,限制应用程序!)。
无论如何,我可以用这种结构实现浮动CSS标签吗?
.test-field {
clear: both;
margin-bottom: 20px;
position: relative;
}
.test-field__input {
font-size: 0.875em;
line-height: 1;
-moz-appearance: none;
-webkit-appearance: none;
background-color: #f5f5f5;
border: 2px solid #eee;
border-radius: 4px;
color: grey;
height: calc((40 / 14) * 1em);
line-height: 1;
outline: 0;
padding: 0 8px;
vertical-align: top;
width: 100%;
}
/* // FOCUS */
.test-field__input:focus,
.test-field__input ~ input:checked:focus {
border-color: #5d7199;
}
/* // DISABLED */
.test-field--disabled .test-field__input {
background-color: #e8e8e3;
cursor: not-allowed;
}
.test-field--disabled .test-field__flag, .test-field--disabled .test-field__label {
color: #d0d0cb;
}
/* // ERROR */
.test-field--error .test-field__input, .test-field--error .test-field__selection .atc-field__input {
border-color: #ff4436;
color: #ff4436;
}
/* // FLOATING LABEL */
.test-field--floating .test-field-input {
position: relative;
margin-bottom: 1.5rem;
}
.test-field__label {
position: absolute;
top: 0;
padding: 7px 0 0 13px;
transition: all 200ms;
opacity: 0.5;
}
.test-field__input:focus + .test-field__label,
.test-field--floating .test-field__input:valid + .test-field__label {
font-size: 75%;
transform: translate3d(0, -100%, 0);
opacity: 1;
}
<div class="test-field test-field--floating">
<label for="a" class="test-field__label">Input label</label>
<input class="test-field__input" id="b" type="text" value="" required>
</div>
【问题讨论】:
-
这能回答你的问题吗? Is there a CSS parent selector?
-
你不能用这种结构的 CSS 来做。该技术基于您根据应用于输入字段的不同伪类来格式化标签 - 但 CSS 只能在 DOM 中选择向右和/或向下,而不是向上或向左。
-
谢谢,我想我找到了另一种方法来完成这项工作
标签: css css-selectors css-transitions css-transforms floating-labels