【问题标题】:Why is the header not fixed while scrolling?为什么滚动时标题不固定?
【发布时间】:2019-06-13 10:59:38
【问题描述】:

我已经尝试了 position:fixed 的 css 属性。我也试过position:sticky, top:0,但标题不固定。

这是我的代码,如你所见,我使用 react 和 antd 作为组件库。

import * as React from "react";
import { render } from "react-dom";
import { Row, Col } from "antd";

import "./styles.css";

function App() {
   return (
     <div>
       <Row className="header">
         <Col
           span={24}
           style={{
             background: "#0392FD",
             position: "sticky",
             top: 0
           }}
         >
          <div>
            <Row>
              <Col>Col1</Col>
              <Col>Col1</Col>
              <Col>Col1</Col>
            </Row>
          </div>
        </Col>
       </Row>
       <Row className="content">
         <Col span={24} style={{ height: "120vh" }}>
           Content
         </Col>
       </Row>
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

这是我的 CSS:

.App {
  font-family: sans-serif;
  text-align: center;
}

我知道有很多解决方案,我尝试了很多。

【问题讨论】:

  • 添加minimal reproducible example 在问题本身,而不仅仅是指向外部资源的链接(可能因其他原因离线、被阻止或无法访问... )
  • 尝试使用位置:固定!重要
  • position: fixed; top: 0; width: 100% 应该可以工作。
  • 您的样式应用于标题内的列,而不是标题 div

标签: css reactjs antd


【解决方案1】:

相反

<Row className="header">
<Col
  span={24}
  style={{
    background: "#0392FD",
    position: "sticky",
    top: 0
  }}
>

你应该这样写

<Row
    className="header"
    style={{
        background: "#0392FD",
        position: "sticky",
        top: 0
      }}
>
<Col span={24}>

Demo

为什么? Col 的父级是 Row。两者的高度相同。 Col 仅在其父级更高且滚动期间 Col 将消失时才会粘住。这永远不会发生,因为正如我所说,它们的高度相同。如果您在Row 上设置position: sticky,哪个父级包含整个页面(父级高于Web 浏览器窗口)position: sticky 将正常工作。

【讨论】:

    【解决方案2】:

    您的代码必须在标题上,而不是在标题内的 div 上

    只需将其添加到您的 style.css 文件中

    .header {
      position: sticky;
      top: 0;
    }
    

    效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多