css如何制作密码
使用CSS隐藏密码输入
在HTML中使用<input type="password">可以隐藏密码输入,但若需进一步自定义样式,可以通过CSS实现。
<input type="password" class="password-field" placeholder="输入密码">
.password-field {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-family: monospace; /* 统一字符宽度 */
letter-spacing: 1px; /* 增加字符间距 */
}
自定义密码显示样式
若需将密码显示为圆点或其他符号,可通过伪元素模拟。但需注意此方法仅改变视觉表现,实际输入值不受影响。
.password-mask {
position: relative;
}
.password-mask::after {
content: "•";
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
切换密码可见性
通过JavaScript配合CSS实现密码显示/隐藏切换功能:
<input type="password" id="password">
<button onclick="togglePassword()">显示密码</button>
function togglePassword() {
const passwordField = document.getElementById("password");
if (passwordField.type === "password") {
passwordField.type = "text";
} else {
passwordField.type = "password";
}
}
密码强度指示器
使用CSS创建视觉化密码强度提示:
<div class="strength-meter">
<div class="strength-bar"></div>
</div>
.strength-meter {
width: 100%;
height: 5px;
background-color: #eee;
}
.strength-bar {
height: 100%;
width: 0%;
transition: width 0.3s, background-color 0.3s;
}
通过JavaScript根据密码长度更新宽度和颜色:
passwordField.addEventListener('input', function() {
const strength = calculateStrength(this.value);
const bar = document.querySelector('.strength-bar');
bar.style.width = strength.percent + '%';
bar.style.backgroundColor = strength.color;
});
密码输入验证样式
为无效密码输入添加视觉反馈:
.password-field:invalid {
border-color: #ff6b6b;
box-shadow: 0 0 5px rgba(255, 0, 0, 0.2);
}
配合HTML5验证模式:

<input type="password" pattern=".{8,}"
title="密码至少8个字符" required>






