首页 > 解决方案 > 如何定位子 div 从父 div 的开头到结尾?

问题描述

我正在尝试将FullWidthDiv组件定位为从MainDiv侧面的开头一直到结尾。我试过在一个绝对位置上放弃并玩弄 flex,但我不能让它不从SubDiv组件开始。

有可能实现这一目标吗?

我的CodeSandbox方法。

是我想要实现的目标

标签: javascriptreactjsflexbox

解决方案


这有点 hacky,但你可以ChildDivalign-items: center.

此外,将 缩小FullWidthDiv到 280。最后,您必须将flex: 1,添加width: 100%到 div 中,该 div 包含在组件SubChildDiv内部App

export default function App() {
  return (
    <MainDiv>
      <ChildDiv>
        <div style={{flex: 1, width: '100%'}}>
          <SubChildDiv />
          <SubChildDiv />
        </div>
        <FullWidthDiv />
      </ChildDiv>
    </MainDiv>
  );
}

const MainDiv = ({ children }) => (
  <div
    style={{
      display: "flex",
      justifyContent: "center",
      alignItems: "center",
      width: 250,
      height: 250,
      backgroundColor: "red",
      padding: "1rem"
    }}
  >
    {children}
  </div>
);

const ChildDiv = ({ children }) => (
  <div
    style={{
      width: 200,
      height: 200,
      backgroundColor: "blue",
      display: "flex",
      flexDirection: "column",
      alignItems: "center",
      justifyContent: "space-between"
    }}
  >
    {children}
  </div>
);

const SubChildDiv = () => (
  <div
    style={{
      display: "flex",
      width: "100%",
      height: 30,
      backgroundColor: "green",
      border: "1px solid black"
    }}
  />
);

const FullWidthDiv = () => (
  <div
    style={{
      width: 280,
      height: 30,
      border: "1px solid black",
      backgroundColor: "green"
    }}
  />
);

如果你想要FullWidthDiv100% 的宽度,你必须计算 100% 的宽度并从它的两侧添加填充,MainDiv看起来像这样calc(100% + 2rem)


推荐阅读