除了样式以外,只经过css的伪类选择器实现了当鼠标焦点在'用户名'或'密码'输入框时,提示信息自动缩小并跑到左上方。如若输入框中没有值,则回到原来的样子,如有值则再也不恢复。css
其基本原理是 css3 提供的伪元素选择器,经过在<input>
标签中增长require
属性(这个属性并非一个键值对),使得当输入框中有内容时会被:valid
选择器选中。至于鼠标焦点还在输入框中时利用的伪类选择器:focus
算是老生常谈了。
但说明输入框内容的<label>
标签并非<input>
标签的子元素,该如何经过<input>
的状态管理<label>
呢?便用到了兄弟选择器~
。eleA ~ eleB
做为选择器时,会选中全部和 eleA 同辈的 eleB 元素。官方文档点此:传送门。html
另外最后被密码输入框的浏览器自动提示曾经的内容搞得烦的一批,搜索了一下能够经过在<input>
标签中添加autocomplete="off"
禁止浏览器作输入框提示,完美。css3
index.html
浏览器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <div id="login-div"> <p id="form-title-p">简单登陆框</p> <form action="" id="login-form"> <div class="input-div"> <input type="text" id="carpoolername-input" required /> <label>用户名</label> </div> <div class="input-div"> <input type="password" id="password" required autocomplete="off" /> <label>密码</label> </div> <div class="btn-div"> <button id="submit-btn" type="button">登陆</button> </div> </form> </div> </body> </html>
index.css
要记得和index.html
的相对位置,自行在index.html
中添加引用。flex
* { padding: 0; margin: 0; } body { background: linear-gradient(127deg, #64c4ed, #fec771); height: 100vh; font-family: "Helvetica Neue", Helvetica, Arial, "Microsoft Yahei", "Hiragino Sans GB", "Heiti SC", "WenQuanYi Micro Hei", sans-serif; } #login-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; flex-direction: column; justify-content: center; align-items: center; color: white; padding: 3vh 3vw; background-color: #8b4367; opacity: .8; outline: none; border: none; border-radius: 10px; box-shadow: 2px 2px 6px #8b4367; } #login-div #form-title-p { font-weight: 500; font-size: 2rem; padding: 10px; margin-bottom: 20px; letter-spacing: 0.5rem; } .input-div { position: relative; padding: 5px; margin-bottom: 2vh; } .input-div, .btn-div { text-align: center; vertical-align: middle; } .input-div input { width: 15vw; height: 5vh; padding: 0 1rem; outline: none; border: none; background-color: transparent; border-bottom: 1px solid black; font-size: 14px; } .input-div label { position: absolute; left: 1rem; top: .5rem; font-size: 16px; transition: 0.2s; } .input-div input:focus ~ label, .input-div input:valid ~ label { left: 0; top: -10px; font-size: 12px; } .btn-div button { outline: none; border: none; margin-top: 3vh; width: 90%; box-sizing: border-box; padding: 10px; border-radius: 8px; box-shadow: 1px 1px 1px #32dbc6; background-color: #49beb7; color: white; font-size: 16px; }