繁体   English   中英

React 页面将页脚保留在页面底部

[英]React page keep footer at the bottom of the page

尝试修复页面底部的页脚时出现问题,如下图所示:

在此处输入图像描述

虽然我用谷歌搜索并看到很多建议,但我仍然面临这个问题。 我怀疑这个问题是<div data-reactroot></div> cannot be set height 100% as its parents。 谁能帮帮我?

提前致谢!

更新:页脚样式:

borderTop: '1px solid #ddd',
height: '60px',
lineHeight: '60px',
backgroundColor: 'white'

您需要告诉页脚将自身定位到周围容器的底部:

页脚CSS:

position:absolute;
left:0;
bottom:0;
right:0;

对于容器(react-root div):

padding-bottom:60px;

作为替代方案(如果您不需要支持 IE 8),您可以在div.container上尝试这种样式:

height: calc(100% - 60px);

对于上述解决方案不适用的任何其他人,您可以尝试以下步骤:

  1. div一个非静态position比如relative (记住默认positionstatic
  2. div 一个最小高度100vh 这使它能够垂直占用所有可用空间
  3. 然后对于页脚( child ),如果不是,则应将其包裹在div ,为其提供以下属性; position: absolute; bottom: 0; width: 100% position: absolute; bottom: 0; width: 100%

更新:在某些情况下,将页脚div positionabsolute可能不起作用。 在这种情况下,请改用relative

希望上面的步骤应该可以解决它:-)

重要的是要有内容包装器并将其最小高度设置为 100vh:

min-height: 100vh; (100% of the viewport height)

min-height: 100%; (100% of the parent's element height)

看看这里解释得很好,对我有用https : //medium.com/@zerox/keep-that-damn-footer-at-the-bottom-c7a921cb9551

您是否正在尝试为您的页面添加一个包装器,以便您绝对可以将页脚定位在底部? 如果是这样,您可以为此创建一个具有相对位置的新组件,并将其他组件作为子项传入,并在底部提供页脚绝对定位。

希望我早点读。 这是Ikechuk答案的片段,请注意,现在footer也尊重边距(可能不在上述任何其他答案中):

 html, body, div{ height:100%; width:100% display:block; } footer{ position:absolute; bottom:0; display:block; width:100% } hr{ display: block; unicode-bidi: isolate; margin-block-start: 0.5em; margin-block-end: 0.5em; margin-inline-start: auto; margin-inline-end: auto; overflow: hidden; border-style: inset; border-width: 1px; }
 <html> <body> <div style={"margin=5%;"}> <div style={"position:relative"}> <footer> <hr> I am footer </footer> </div> </div> </body> </html>

我相信这里每个人都缺少的一个技巧是,在 React 中,在 html 和 body 元素之后,还有一个带有#root的 div,它包含了整个内容。 请参考下图。

在此处输入图片说明

因此,需要使高度 100% 的所有 3 即 html、body 和 #root。

html, body, #root {
  height: 100%;
}

然后在#root 中添加这些属性:

#root {
 display: flex;
 flex-direction: column;
}

你一定想知道为什么 #root 需要是 flex 而不是 body。 原因是它是最里面的父级,或者我应该说是页脚的最接近的父级。

现在,最后只为页脚执行此操作:

footer: { margin-top: auto }

上面一行的作用是将页脚推到其父级的末尾。 就这么简单。 这里没什么好看的。 无需对高度进行任何计算或更改页脚的位置。

我会按如下方式更改页脚 css:

  position: fixed;
  left:0;
  bottom:0;
  right:0;

可以有一个position: absolute但它不会滚动友好。

弹性成长

聚会很晚了,但我的解决方案是:

<div className="layout">
  <Navbar />
    <main>
      {children}
    </main>
  <Footer />
</div>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.layout main {
  flex-grow: 1;
}

谢谢,@mwoelk 回答了问题。 我只是想让初学者更清楚。

第 1 步 --- 页脚 css:

.Footer {
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
}

Step 2 --- Wraper of Footer css:(以React为例,通常footer是包裹在.App里面的。之所以添加padding bottom是为了避免底部的Footer覆盖部分内容,如果content是太长。)

.App {
  padding-bottom: 60px;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM