案例来源
本例来自CodingStartup的视频:[HTML+CSS] 动态显示表单栏位标题
案例演示
知识总结
因为本例实现的效果是点击文本框,提示信息移动到文本框左边,当用户输入完信息,提示信息移动回文本框并隐藏,所以本例使用了label元素作为提示信息。
根据上面的想法,就有了一下几个实现的关键点:
如何将label放在文本框输入位置
如何将提示信息移动
在文本框有文字时如何隐藏提示信息
本例在input中使用了padding,控制了文本框中文字出现的位置,所以只需要设置label相对于父元素的left和top即可,值与前面padding值对应。
使用input元素的:focus伪类,设置兄弟元素label的移动,其中移动使用了transform: translateX(calc(-100% - 2.5rem));,这里的-100%表示向反方向移动自身的宽度。可以看到这里使用了calc()函数,它可以进行简单的计算。
注意:运算符-左右要有空格。
在隐藏提示信息处使用了input:not(:focus):not(:placeholder-shown),表示input在没有选中的时候并且placeholder没有显示的时候(也就是说文本框由内容的时候)对兄弟元素label进行隐藏。
注意:input的placeholder属性值不能为空,可以加空格。
主要代码
html
用户登录
用户名称
密码
css
html {
font-size: 15px;
}
body {
margin: 0;
font-family: Helvetica;
background-color: #29f1c3;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.row {
width: 600px;
margin: .6rem 0;
position: relative;
}
.row input {
font-size: 1rem;
border: 1px solid #03c9a9;
border-radius: 4px;
margin: 0;
padding: .8rem 1rem;
box-shadow: 0px 1px 2px rgba(0,0,0,.25);
width: 100%;
box-sizing: border-box;
color: #2e3131;
outline: none;
transition: all ease-in-out .2s;
}
.row label {
position: absolute;
left: 1rem;
top: .8rem;
color: #ccc;
transition: all ease-in-out .2s;
}
h2 {
font-size: 2rem;
letter-spacing: .1rem;
margin-bottom: 2rem;
}
.row input:focus {
border: 1px solid #1ba39c;
}
.row input:focus + label {
transform: translateX(calc(-100% - 2.5rem));
color: #2e3131;
}
input:not(:focus):not(:placeholder-shown) + label {
color: rgba(0,0,0,0);
}