【问题标题】:How to fix position of one element in a flexbox?如何固定一个元素在弹性框中的位置?
【发布时间】:2021-04-13 16:31:58
【问题描述】:

我有 2 个框:面板和侧边栏,在一个弹性框中,带有 flex-direction: rowjustify-content: space-between 我可以将它们并排水平对齐,中间有一个间隙。

现在我想修复右侧边栏的位置,即当向下滚动时,边栏应始终保持在屏幕顶部,无论面板的位置如何。我怎样才能用 CSS 做到这一点?

这里的工作示例:https://codesandbox.io/s/gallant-saha-zgmnw

代码在这里:

App.js:

import React from "react";
import "./App.scss";
import Panel from "./Panel";
import Sidebar from "./Sidebar";

export default function App() {
  return (
    <div className="App">
      <Panel />
      <Sidebar />
    </div>
  );
}

App.scss:

.App {
  width: 1100px;
  font-family: sans-serif;
  text-align: center;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

Panel.js:

import React from "react";
import "./Panel.scss";

const Panel = () => {
  return (
    <>
      <div className="panel">The main panel</div>
    </>
  );
};

export default Panel;

Sidebar.js:

import React from "react";
import "./Sidebar.scss";

const Sidebar = () => {
  return (
    <>
      <div className="sidebar">The sidebar</div>
    </>
  );
};

export default Sidebar;

【问题讨论】:

  • 使用绝对或粘性
  • @DCR 可以与父母 display: flex 一起使用吗?
  • 显示:弹性;位置:相对;然后在你想要放置的元素中使用 position:absolute

标签: javascript reactjs flexbox


【解决方案1】:

将此css添加到.sidebar

position:fixed;
right: 10px;

另外,您可以添加:

top: -- px

如果你有导航栏。

【讨论】:

    【解决方案2】:

    我修改了你的侧边栏 CSS。 我使用了固定位置,因为这会使侧边栏固定在视口中,因此当您滚动时它会保持静止。

    .sidebar {
      position: fixed;            /* add this */
      width: 200px;
      height: 200px;
      text-align: center;
      border: 1px black solid;
      left: 906px                /* add this */
    }
    

    这会产生预期的效果。测试和工作。抱歉,我已经更新了我的答案。

    【讨论】:

    • 侧边栏确实贴在屏幕顶部,但right: 0px 让它贴在页面右侧,这与原始设计不同
    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多