如何用Flexbox实现登录页面全屏高度并保持响应式?
问题描述
我需要用Flexbox实现登录页面占满电脑屏幕100%高度,同时保持响应式。目前Chrome浏览器中的登录页面存在空白区域,我已经尝试调整html和body标签但没有效果。
前端代码(React)
const SignIn = () => { return ( <RuxContainer className="container"> <div slot="header" className="header-container"> <h3 className="first-header-item">LOGO</h3> <RuxClock timezone="Z"></RuxClock> <RuxMonitoringIcon status="normal"></RuxMonitoringIcon> </div> <div className="body-container"> <form className="rux-form"> <h2 className="body-sign-in">SIGN IN</h2> <h6>Measure your success in the Space Force!</h6> <div className="sign-in-inputs"> <rux-input id="email" placeholder="Email@astro.com" label="Email" type="email" ruxblur="{handleValidation()}" ></rux-input> <rux-input id="pw" label="Password" type="password"></rux-input> </div> <div className="sign-in-helper-functions"> <rux-checkbox class="checkbox">Remember me</rux-checkbox> <p className="forgot-password">Forgot Password?</p> </div> <div className="sign-in-container"> <rux-button className="sign-in-btn" type="submit"> Sign in </rux-button> </div> </form> </div> <div slot="footer" className="footer"> <p>hi</p> </div> </RuxContainer> ); }; export default SignIn;
CSS代码
body { margin: 0; } .header-container { display: flex; justify-content: space-between; align-items: center; } .body-container { display: flex; flex-direction: column; align-items: center; } .rux-form { width: 30%; max-width: 430px; } .sign-in-helper-functions { display: flex; justify-content: space-between; margin-top: 10px; } .forgot-password { margin: 0; color: white; text-decoration: underline; text-decoration-color: #1976d2; } .sign-in-container { display: flex; justify-content: end; width: 100%; margin-top: 20px; } .footer { background-color: #172635; }
解决方法
要让页面占满屏幕100%高度并消除空白,得从根节点到容器层都配置正确的Flexbox规则,具体调整如下:
- 先给html和body设置全高度,同时把body设为Flex容器,让子元素能自动分配空间:
html, body { height: 100%; margin: 0; padding: 0; } body { display: flex; flex-direction: column; }
- 给容器
.container设置最小高度为视口高度,同时用Flex布局分配内部空间:
.container { display: flex; flex-direction: column; min-height: 100vh; width: 100%; }
- 让
.body-container填充header和footer之外的所有剩余空间,还能让表单垂直居中:
.body-container { display: flex; flex-direction: column; align-items: center; justify-content: center; flex-grow: 1; width: 100%; }
- 确保footer固定在底部,宽度拉满:
.footer { background-color: #172635; width: 100%; }
调整后,页面会完全占满屏幕高度,中间的登录区域自动填充空白空间,表单垂直居中,同时保持响应式特性,小屏幕下也能正常显示。
内容的提问来源于stack exchange,提问作者SupraCoder
相关产品推荐
相关产品推荐

