CSS与HTML实现输入框标签变换后固定位置的问题求助
解决输入框标签随内容保留上移状态的问题
要实现输入框有内容时标签固定在上方,只需利用CSS的:not(:placeholder-shown)伪类,结合原有的:focus状态,让两种情况都触发标签的上移样式。具体操作如下:
给输入框添加空占位符
在<input>标签中加入placeholder=""——:not(:placeholder-shown)需要占位符属性存在才能生效,即使内容为空也不影响。扩展CSS选择器
将原有的仅针对:focus的样式规则,扩展为同时匹配:focus和:not(:placeholder-shown)状态,确保输入框有内容时标签保持上移。
修改后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .input[type="email"] { display: block; border: 1px solid rgb(228, 228, 228); font-size: 16px; width: 20%; height: 55px; padding: 0 15px; margin-bottom: 10px; position: relative; z-index: 2; background-color: transparent; outline: none; border-radius: 5px; } .inputs { position: relative; } .input-label { position: absolute; top: 15px; font-size: 1.1rem; left: 14px; color: rgb(122, 122, 122); font-weight: 100; transition: 0.1s ease; background-color: white; padding: 0 5px; } /* 同时匹配聚焦和有内容的状态 */ .input[type="email"]:focus~.input-label, .input[type="email"]:not(:placeholder-shown)~.input-label { top: -7px; color: #18c9c0; font-size: 13px; background-color: rgb(255, 255, 255); z-index: 2; } .input[type="email"]:focus { border: 2px solid #afff03; } </style> <title>Document</title> </head> <body> <div class="inputs"> <input type="email" name="" id="email" class="input" placeholder=""> <label for="email" class="input-label">Enter Text</label> </div> </body> </html>
关键说明
:not(:placeholder-shown):当输入框内有内容(占位符不显示)时,该伪类匹配输入框,触发标签的上移样式。- 合并两个选择器后,输入框在聚焦或有内容两种状态下,标签都会保持上移后的位置,不会和输入内容重叠。
内容的提问来源于stack exchange,提问作者Abdul Rafay Shaikh
相关产品推荐
相关产品推荐

