实现效果
实现方法
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style-1.css">
</head>
<body>
<div class="edit-group">
<input class="edit-input">
<label class="eidt-label">账号</label>
</div>
</body>
</html>
html代码非常简单但请注意lable必须写在input标签下面,防止在使用绝对布局定位时input会覆盖 label;
css代码
首先给全局元素设为IE盒模型方便操作
*,
::after,
::before{
box-sizing: border-box;
}
将容器设置相对定位,以创建定位上下文,便于lable定位:
.edit-group{
position: relative;
}
给lable和input元素设置相同的高度:
.edit-group .edit-input,
.edit-group .eidt-label{
height:2rem;
}
设置输入框样式以及选中时的样式:
.edit-input{
border-radius: .2em;
border:1px solid #495057;
}
.edit-group .edit-input:focus{
border-style:solid;
border-color: #80bdff;
border-width: 2px;
outline: none;
}
设置lable的样式:
.eidt-label{
position:absolute;
top: 0;
left:4px;
padding:2px;
line-height: calc(2rem + -4px);/*-4px是因为文字上下间距不相同,-4dp使文字居中*/
transition: all .2s ease-in-out;
color: #495057;
background-image: linear-gradient(transparent,transparent 50%, white 50%);/*当获取到焦点时移动到边框上,设置一般透明背景使露出文字的地方透明,一半是白色更方便盖住边框*/
background-clip: content-box;/*设置背景扩展到的位置,防止盖住边框*/
-webkit-background-clip: content-box;
}
当获取焦点后将lable移动到边框上,缩小文字,颜色减淡:
.edit-group .edit-input:focus + .eidt-label{
top: -1rem;
font-size:0.5rem;
color: #495057;
}
完整代码
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style-1.css">
</head>
<body>
<div class="edit-group">
<input class="edit-input">
<label class="eidt-label">账号</label>
</div>
</body>
</html>
css
*,
::after,
::before{
box-sizing: border-box;
}
.edit-group{
position: relative;
}
.edit-group .edit-input,
.edit-group .eidt-label{
height:2rem;
}
.eidt-label{
position:absolute;
top: 0;
left:4px;
cursor: text;
pointer-events: none;
padding:2px;
line-height: calc(2rem + -4px);
transition: all .2s ease-in-out;
color: #495057;
background-image: linear-gradient(transparent,transparent 50%, white 50%);
background-clip: content-box;
-webkit-background-clip: content-box;
}
body{
background-color: beige;
}
.edit-input{
border-radius: .2em;
border:1px solid #495057;
}
.edit-group .edit-input:focus{
border-style:solid;
border-color: #80bdff;
border-width: 2px;
outline: none;
}
.edit-group .edit-input:focus + .eidt-label{
top: -1rem;
font-size:0.5rem;
color: #495057;
}