css 如何在reactjs中设置粘性导航条

ruyhziif  于 2023-02-26  发布在  React
关注(0)|答案(5)|浏览(166)

我的导航栏隐藏了下面的内容。而且,它粘在左边而不是中间部分。我希望有人能告诉我正确的方法来使导航栏正确的方法来使粘性导航栏停留在它的位置,即使我们正在滚动。
代码sanbox https://codesandbox.io/s/clever-voice-24udr
Navbar.js

import React, { Fragment } from "react";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";

const NavbarPage = () => {
  const guestLinks = (
    <ul>
      <li>
        <Link to="/">
          <Button className="btn btn-primary createNew">Create New</Button>
        </Link>
      </li>
      <li>
        <Link to="/about">
          <Button className="btn btn-danger signOut">Sign out</Button>
        </Link>
      </li>
    </ul>
  );
  return (
    <nav className="navbar bg-white">
      <h3 className="titleName">
        <Link to="/">
          <i className="fas fa-pen" /> demo
        </Link>
      </h3>
      {guestLinks}
    </nav>
  );
};

export default NavbarPage;
.navbar {
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.7rem 2rem;
  overflow: hidden;
  z-index: 1;
  width: 88.15%;
  margin: auto;
  top: 0;
  border-bottom: solid 1px var(--primary-color);
  opacity: 0.9;
  top: 0;
  box-shadow: 12px 0 15px -4px rgba(31, 73, 125, 0.8),
    -12px 0 8px -4px rgba(31, 73, 125, 0.8);
  box-shadow: 0 9px 0px 0px white, 0 -9px 0px 0px white,
    12px 0 15px -4px rgba(31, 73, 125, 0.8),
    -12px 0 15px -4px rgba(31, 73, 125, 0.8);
}
ejk8hzay

ejk8hzay1#

只是想知道您是否可以使用position: sticky; top: 0来做同样的事情。
纯CSS会更快

elcex8rz

elcex8rz3#

在CSS中进行这些更改

.navbar {
      position: fixed;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0.7rem 2rem;
      overflow: hidden;
      z-index: 1;
      width: 100%; 
      margin: auto;
      top: 0;
      border-bottom: solid 1px var(--primary-color);
      opacity: 0.9;

      position: fixed;
      top: 0;

      /* box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.25); */
      box-shadow: 12px 0 15px -4px rgba(31, 73, 125, 0.8),
        -12px 0 8px -4px rgba(31, 73, 125, 0.8);
      box-shadow: 0 9px 0px 0px white, 0 -9px 0px 0px white,
        12px 0 15px -4px rgba(31, 73, 125, 0.8),
        -12px 0 15px -4px rgba(31, 73, 125, 0.8);
    }

.conMain {
  height: 130vh;
  margin-top: 100px; //you need to add margin for your layout main 
  container
  width: 100%;
  box-shadow: 12px 0 15px -4px rgba(31, 73, 125, 0.8),
    -12px 0 8px -4px rgba(31, 73, 125, 0.8);
  box-shadow: 0 9px 0px 0px white, 0 -9px 0px 0px white,
    12px 0 15px -4px rgba(31, 73, 125, 0.8),
    -12px 0 15px -4px rgba(31, 73, 125, 0.8);
}

希望这对你有帮助。

3mpgtkmj

3mpgtkmj4#

这也适用于React组件:

position: sticky;
top: 0
qvk1mo1f

qvk1mo1f5#

对我很有效-

position: fixed;

top: 0;

相关问题