简体   繁体   English

如何在 Next.js (React) 中制作粘性页脚

[英]How do I make a sticky footer in Next.js (React)

I want to make a sticky footer that will stick to the bottom if there's not enough content to fill up the whole page.如果没有足够的内容来填满整个页面,我想制作一个粘性页脚,它会粘在底部。 I've searched up ways to do it in CSS, but a lot of them doesn't translate to React/Next since it involves messing with the html and body tag.我已经搜索了在 CSS 中执行此操作的方法,但其中很多方法并没有转换为 React/Next,因为它涉及弄乱 html 和 body 标签。 I'm wondering if there are other ways to do it.我想知道是否有其他方法可以做到这一点。

Here is the JSX for my Footer:这是我的页脚的 JSX:

     <div>
        <footer>
          <a href={"https://www.instagram.com/linghandmade18/"}>
            <i className="fab fa-instagram" />
          </a>
        </footer>
        <h2>Some Text</h2>
      </div>

Here is my Layout file for Next.js:这是我的 Next.js 布局文件:

const Layout = (props) => {
  return (
    <div>
      <Navbar />
      {props.children}
      <Footer />
    </div>
  );
};

If you don't want to mess with html and body tags then you need a container on which you can apply your style.如果您不想弄乱 html 和 body 标签,那么您需要一个可以应用您的样式的容器。 So first of all create a common container inside your Layout (add container class to parent element), like this:因此,首先在您的布局中创建一个公共容器(将容器类添加到父元素),如下所示:

const Layout = (props) => {
  return (
    <div class="container">
      <Navbar />
        {props.children}
      <Footer />
    </div>
  );
};

Now you have a .container class to the div which is parent div of Navbar, Content and Footer.现在你有一个.container类到 div,它是.container 、内容和页脚的父 div。 Now add following styles to the container class:现在将以下样式添加到容器类:

.container {
  min-height: 100vh;
  position: relative;
}

Because of this your container height will stay at least 100vh (viewport height), it will grow more if content length increases.因此,您的容器高度将至少保持 100vh(视口高度),如果内容长度增加,它会增长得更多。

And for your footer component, make these changes if the h2 is part of the footer (for better accessibility).对于您的页脚组件,如果 h2 是页脚的一部分(以获得更好的可访问性),请进行这些更改。

const Footer = (
  <footer>
    <a href={"https://www.instagram.com/linghandmade18/"}>
      <i className="fab fa-instagram" />
    </a>
    <h2>Some Text</h2>
  </footer>
);

For footer styling you can add this style:对于页脚样式,您可以添加以下样式:

footer {
  position: absolute;
  bottom: 0;
  left: 0;
}

This way it will always stay in the bottom position regardless of the content height.这样,无论内容高度如何,它都将始终保持在底部位置。

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

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