[英]Footer won't stay at bottom of page and below content in React
我有一个具有这种基本布局的 React 应用程序:
function App() {
return (
<div className="app">
<Header />
<Main />
<Footer />
</div>
);
}
export default App;
我的问题是我为每个组件都有单独的样式表,但我不能让我的页脚既位于页面底部,又始终位于内容下方。 也就是说,如果页面为空白,页脚仍将位于底部,如果有大于视口高度的内容,页脚仍将保留在其下方。
我已经看到了这个问题的答案,但仅限于常规的 HTML 页面,而不是具有不同样式表的不同 React 组件。 我的每个应用程序组件都有一个index.css
、 App.css
和 CSS 页面。
有没有办法我应该 go 关于它? 我应该添加哪个样式表以使页脚保持在内容的底部和下方。 我目前在Footer.css
中有代码,但代码不会将页脚保留在页面底部和内容下方。
我认为问题在于通常所有组件都位于body
内的同一个 HTML 页面上,但 React 的分解方式略有不同。 任何帮助都会很棒。
例如,您可以在index.css
中添加以下行。 如果需要,您可以将 auto 更改为固定值,例如 100px。
.app {
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
gap: 3rem;
}
这样就可以了。 此外,您可以确保没有来自外部的padding
或margin
,我的意思是具有root
id、 body
和html
的 div,以避免任何不必要的水平滚动。
您需要将样式添加到全局容器:
html,body,#root {
display: flex;
flex-direction: column;
min-height: 100%;
}
然后将样式添加到您的页脚组件:
.footer {
padding-top: auto;
}
我不建议使用
min-height: 100vh;
由于其计算方式,它将在移动设备上中断。
在index.css
添加:
Footer {
width: 300px;
text-align: center;
position: relative;
bottom: 0;
left: 50%;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
示例: https ://codesandbox.io/embed/quirky-sound-bitt9k?fontsize=14&hidenavigation=1&theme=dark
您可以更改position: fixed;
如果您希望页脚部分相对于视口显示在页面底部,而不是相对于页面内容。
供您参考的来源:
https://getridbug.com/html/transform-translate-50-50/ https://www.w3schools.com/css/css_positioning.asp
我在使用 grid 和 grid-template-rows 时遇到了问题,但切换到 flex 就成功了。
我的理解是使用flex-direction: column;
和justify-content: space-between;
分隔我的三个组件并强制我的<Footer />
在<Main />
> 下面,无论视口高度如何。
如果有人更好地理解为什么我的答案比其他人更好,我希望得到解释。
index.css 文件:
.app {
min-height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.