Vue3登录页面密码显示/隐藏按钮样式适配问题求助
解决Vue3登录页密码框与显示/隐藏按钮布局问题
问题根源
你当前的表单元素都放在了flex-direction: column的容器里,导致密码输入框和显示按钮是垂直排列,而非预期的左右贴合。同时按钮的固定宽度设置也干扰了输入框的布局表现。
修复步骤
- 重构模板结构:将密码输入框和显示/隐藏按钮包裹在一个单独的横向flex容器中,让它们并排显示。
- 调整CSS样式:给新容器设置合适的flex布局,让按钮紧贴输入框右侧,同时匹配输入框的高度。
- 优化按钮样式:去掉按钮的固定宽度,改为自适应内容,避免占用多余空间。
修改后的完整代码
<template> <div class="rel-position flex"> <div class="main-element accent box rel-position"> <form @submit.prevent="Login"> <div class="rel-position flex"> <select class="main-element rel-position clickible clickible-color login-input n-font"> <option value="Albany">Albany</option> <option value="Walnut Creek">Walnut Creek</option> </select> <input class="main-element rel-position clickible login-input n-font" type="text" placeholder="Username" required v-model="username"> <!-- 新增包裹密码框和按钮的容器 --> <div class="password-input-wrapper"> <input class="main-element rel-position clickible login-input n-font" :type="showPassword === true ? 'text' : 'password'" placeholder="Password" required v-model="password"> <button class="main-element rel-position clickible n-font" id="toggle-button" type="button" @click="showPassword = !showPassword"> <svg width="24" height="24" v-if="showPassword"> <!-- 显示密码的SVG图标 --> </svg> <svg width="24" height="24" v-else> <!-- 隐藏密码的SVG图标 --> </svg> </button> </div> <button class="main-element rel-position clickible clickible-color login-input n-font" type="submit">Login</button> </div> </form> </div> </div> </template> <script setup lang="ts"> import { ref } from 'vue'; const username = ref(''); const password = ref(''); const showPassword = ref(false); function Login() { // 登录逻辑 // 此处编写登录代码 }; </script> <style scoped> .box { margin: 5% 10%; width: 80%; } .flex { width: 100%; display: flex; align-items: center; flex-direction: column; } .login-input { height: 5vh; width: 35%; margin-bottom: 5%; } /* 新增密码框容器样式 */ .password-input-wrapper { display: flex; align-items: center; width: 35%; margin-bottom: 5%; } /* 调整密码输入框,去掉margin-bottom,让容器来控制间距 */ .password-input-wrapper .login-input { width: 100%; margin-bottom: 0; border-right: none; /* 可选:去掉输入框右侧边框,和按钮无缝衔接 */ } #toggle-button { display: flex; height: 5vh; /* 和输入框高度一致 */ width: auto; /* 自适应内容宽度 */ padding: 0 10px; border-left: none; /* 可选:去掉按钮左侧边框,和输入框无缝衔接 */ justify-content: center; align-items: center; } </style>
关键说明
- 新增的
.password-input-wrapper容器使用flex横向布局,让密码框和按钮并排,同时保持和其他表单元素相同的宽度(35%)。 - 调整密码框的
margin-bottom为0,由容器统一控制底部间距,避免重复间距。 - 按钮高度设为和输入框一致(5vh),宽度改为自适应,避免固定宽度破坏布局。
- 可选的边框调整可以让输入框和按钮看起来更像一个整体。
内容的提问来源于stack exchange,提问作者Eli Sterken
相关产品推荐
相关产品推荐

