@rempei

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ヘッダーの固定

解決したいこと

画像のようなヘッダーを作ってみました。

image.png

スクロールすると緑ヘッダーは画面外に行きますが、
黒帯は画面に残るようにしました。しかし、画像のように
緑ヘッダー文の空白ができてしまいます。
どうすれば治るでしょうか?

image.png

該当するソースコード

import React, { useEffect, useState } from "react";
import "./Header_sw.css";

const Header1 = () => {
  return <div className="header-1">Header 1<br></br>Header 1</div>;
};

const Header2 = () => {
  const [isSticky, setIsSticky] = useState(false);
  const [top, setTop] = useState(0);

  useEffect(() => {
    const header1 = document.querySelector(".header-1");
    setTop(header1.offsetHeight);

    const handleScroll = () => {
      if (window.pageYOffset > header1.offsetTop + header1.offsetHeight) {
        setIsSticky(true);
      } else {
        setIsSticky(false);
      }
    };
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <div className={`header-2${isSticky ? " sticky" : ""}`} style={{ top }}>
      Header 2
    </div>
  );
};

export default function Header_sw() {

  return (
    <>
      <Header1 />
      <Header2 />
      
      <div className="content">
        {[...Array(50)].map((_, i) => (
          <p key={i}>Content {i + 1}</p>
        ))}
      </div>
    </>
  );
}

例)

.header-1 {
  height: 100%;
  background-color: green;
  margin-bottom: 100px;
}

.header-2 {
  height: 80px;
  background-color: rgba(0, 0, 0, 0.7);
  position: absolute;
  left: 0;
  right: 0;
  transition: top 0.3s ease;
  z-index: 10;
} 

.header-2.sticky {
  /* top: 0;
  left: 0; */
  position: fixed;
}

自分で試したこと

いろいろいじってみたのですがなかなか思い通りになりません。

0 likes

1Answer

そんな面倒なことしなくてもCSSにposition:stickyがあります.
Chrome 56以降サポートなので互換性とかはそんなに気にしなくていいです.

注意点として,topを指定しないと画面上部に留まってくれないので適宜修正してください.

0Like

Your answer might help someone💌