首页 > 解决方案 > 如何仅在输入聚焦时显示标签

问题描述

标签覆盖了我的输入。单击输入后,我仍然希望看到带有Dupsko内容的标签,但是在我的输入上。

div {
    position: relative;
    background-color: rgba(38, 50, 56, 0.31);
    transition: all 250ms cubic-bezier(0.35, 0, 0.25, 1);
}

label {
    padding-left: 8px;
    position: absolute;
    text-overflow: ellipsis;
    overflow: hidden;
    cursor: text;
    z-index: -10;
}

input {
    outline: none;
    border: none;
    background-image: none;
    background-color:  transparent;

    width: 100%;
    padding: 8px;
    border-bottom: 1px solid #263238;;
    transition: all 250ms cubic-bezier(0.35, 0, 0.25, 1);
}

input:focus {
    background-color: #263238;
    border-bottom: 2px solid #3FBA84;
    color: #FFFFFF;
}

input:focus ~ label {
    position: unset;
    color: #3FBA84;
}
<div>
  <label>Dupsko</label>
  <input>
</div>

仅当输入有焦点时,如何将样式应用于此标签?

标签: htmlcss

解决方案


input:focus ~ label选择label前面有一个元素的每个input:focus元素。因此,您需要更改 html 中两个元素的顺序。另外,我移动了

position: absolute;

from labeltoinput以便input将堆叠在label.

div {
    position: relative;
    background-color: rgba(38, 50, 56, 0.31);
    transition: all 250ms cubic-bezier(0.35, 0, 0.25, 1);
}

label {
    padding-left: 8px;
    overflow: hidden;
    cursor: text;
    text-overflow: ellipsis;
}

input {
    position: absolute;
    outline: none;
    border: none;
    background-image: none;
    background-color:  transparent;

    width: 100%;
    padding: 8px;
    border-bottom: 1px solid #263238;;
    transition: all 250ms cubic-bezier(0.35, 0, 0.25, 1);
}

input:focus {
    background-color: #263238;
    border-bottom: 2px solid #3FBA84;
    color: #FFFFFF;
    z-index: -1;
}

input:focus ~ label {
    position: unset;
    color: #FFFF;
    z-index: 1;
}
<div>
  <input><label>Dupsko</label>
</div>


推荐阅读