CSS鼠标悬停过渡效果失效:登录表单无过渡直接变更尺寸
问题:登录表单悬停时无过渡动画,直接切换尺寸
我希望鼠标悬停在登录表单上时触发过渡动画,但当前悬停时表单直接切换到目标尺寸,没有过渡效果。请问我哪里操作有误?是只需修改CSS中的某个简单设置,还是需要重写全部代码?
原代码
CSS代码
.loginform, .signform { padding: 15px; margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #908168; border: 5px solid; border-color: #241e21; transition: all 2s; } .loginform:hover, .signform:hover { width: 700px; height: 300px; }
HTML代码
<body class="bodyFile"> <div class="loginform"> <h3 class="titleL">Login</h3> <div class="box"> {% with messages = get_flashed_messages() %} {% if messages %} <div class="notification">{{ messages[0] }}</div> {% endif %} {% endwith %} <form method="POST" action="/login"> <div class="field"> <div class="control"> <input class="formtxt" type="email" name="email" placeholder="Your Email" autofocus=""/> </div> </div> <div class="field"> <div class="control"> <input class="formtxt" type="password" name="password" placeholder="Your Password" /> </div> </div> <div class="field"> <label class="checkbox"> <input type="checkbox" /> Remember me </label> </div> <button class="myBtn">Login</button> </form> </div> </div> </body>
解决方法
问题出在没有给表单元素设置初始的width和height。CSS过渡动画需要元素有明确的起始属性值,当你没设置初始宽高时,浏览器会根据内容自动计算尺寸,此时hover状态下直接设置宽高,浏览器无法识别起始状态,就会直接跳变,不会触发过渡效果。
只需修改CSS,给.loginform和.signform添加初始宽高即可,比如:
.loginform, .signform { padding: 15px; margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #908168; border: 5px solid; border-color: #241e21; /* 添加初始宽高,值可根据需求调整 */ width: 400px; height: 250px; transition: all 2s; } .loginform:hover, .signform:hover { width: 700px; height: 300px; }
这样设置后,元素有了明确的起始宽高,hover时的尺寸变化就会触发2秒的平滑过渡动画。
内容的提问来源于stack exchange,提问作者Jacob Ptak
相关产品推荐
相关产品推荐

