最近看到一个 input 框漂浮的 placeholder效果,当 input 聚焦时
Username在 input 框中间,聚焦时漂浮上去,觉得挺有意思的,我们来看看如何通过纯 CSS 实现它。
html 部分
<div class="input-box">
<input type="text" class="input" placeholder=" " />
<label class="placeholder">
Username
</label>
</div>
css 部分
<style>
* {
padding: 0;
margin: 0;
}
body {
background-color:#fff;
height: 100%;
width: 100%;
padding: 50px;
}
.input-box {
position: relative;
}
.input {
padding: 10px;
background-color: #fff;
border-radius: 3px;
outline: none;
color: #444;
border: 1px solid blue;
}
.placeholder {
position: absolute;
top: 8px;
left: 8px;
font-size: 14px;
padding: 0 5px;
color: blue;
transition: .3s;
pointer-events: none;
}
input:focus + .placeholder,
input:not(:placeholder-shown) + .placeholder {
top: -10px;
background-color: #fff;
border-radius: 3px;
}
</style>
最主要的就是这段代码
input:focus + .placeholder,
input:not(:placeholder-shown) + .placeholder {
top: -10px;
background-color: #fff;
border-radius: 3px;
}
这里我们拆开来看:
-
input:focus + .placeholder这是选择器的第一部分。它选择在输入框(input)获取焦点时紧接其后的兄弟元素中的占位符元素(使用类名 .placeholder)。 -
input:not(:placeholder-shown) + .placeholder这是选择器的第二部分。当输入框不是处于占位符状态时(即有输入内容),紧接着的兄弟元素中的占位符元素上移。
一起交流
不管你遇到什么问题,或者是想交个朋友一起探讨技术(=。=),都可以加入我们的组织,和我们一起 ~
喜欢这部分内容,就加入我们的QQ群,和大家一起交流技术吧~
QQ群:1032965518