要实现一个登css实现让登录框始终处于页面的中心位置
要实现一个登录框始终位于页面的中心位置,你可以使用CSS的多种方法。下面是一些常用的方法:
方法1:使用Flexbox
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Centered Login Form</title> <style> body, html { height: 100%; margin: 0; display: flex; justify-content: center; align-items: center; background-color: #f0f0f0; } .login-form { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } </style> </head> <body> <div> <h2>Login</h2> <form> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Login"> </form> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Centered Login Form</title> <style> body, html { height: 100%; margin: 0; display: grid; place-items: center; /* This is a shorthand for align-items and justify-items */ background-color: #f0f0f0; } .login-form { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } </style> </head> <body> <div> <h2>Login</h2> <form> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><br> <label for="password">Password:</label> <input type="password" id="password" name="password"><br><br> <input type="submit" value="Login"> </form> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Centered Login Form</title> <style> body, html { height: 100%; margin: 0; } .login-form { position: absolute; /* or fixed */ top: 50%; /* positions the top edge of the element at the middle of the parent */ left: 50%; /* positions the left edge of the element at the middle of the parent */ transform: translate(-50%, -50%); /* moves the element back by its own width and height */ background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } </style> </head> <body> <div> <h2>Login</h2> <form> <label for="username">Username:</label> <input type="text" id="username" name="username"><br><
// 首先需要获取登录框的整体高度,设置父元素高度宽度为100%,这里假设高度为登录框高度为500px .container{ width:100%; height:100%; } .login{ margin:calc((100% - 500px)/2) auto; }