React项目如何将Footer固定在页面底部?无内容不居中、有内容不遮挡
解决方案
你需要实现粘性页脚效果:页面内容不足一屏时,Footer固定在视口底部;内容超过一屏时,Footer跟随内容排在页面最底部,不会遮挡上层元素。
调整全局样式
在原有全局样式基础上补充根元素高度配置:
* { margin: 0; padding: 0; box-sizing: border-box; } /* 新增以下代码 */ html, body, #root { height: 100%; }
修改落地页主入口代码
给整个页面加flex布局容器,让主体内容区域自动撑开剩余高度:
import React from "react"; import styled from "styled-components"; import Footer from "../Components/Footer"; import NavBar from "../Components/NavBar"; import ReviewSection from "../Components/ReviewSection"; const LandingPage = () => { return ( <PageContainer> <NavBar /> <MainContent> <ReviewSection /> {/* 后续其他页面内容都放在这个容器里 */} </MainContent> <Footer /> </PageContainer> ); }; const PageContainer = styled.div` display: flex; flex-direction: column; min-height: 100vh; `; const MainContent = styled.div` flex: 1; `; export default LandingPage;
修改Footer组件样式
去掉Bigdiv的定位属性,不需要固定定位:
// 只需要修改Bigdiv的样式,其他代码不变 const Bigdiv = styled.section` width: 100%; @media (max-width: 600px) { font-size: 12px; } `;
完成以上修改后即可实现预期效果:内容不足时Footer贴在视口底部,内容超出时Footer跟在内容末尾,不会遮挡上层元素。
内容的提问来源于stack exchange,提问作者Syed Muhammad Moiz
相关产品推荐
相关产品推荐

