【问题标题】:How to position a child div to span from the beginning to the end of a parent div?如何定位子 div 从父 div 的开头到结尾?
【发布时间】:2020-08-10 21:49:14
【问题描述】:

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

有可能实现吗?

我的CodeSandbox 方法。

Here 是我想要实现的目标

【问题讨论】:

  • 我不知道 FullWidthDiv 从哪里开始。代码看起来不完整。
  • 在 CodeSandbox 链接的第 12 行
  • 这似乎有点“hacky”,但您可以使用负边距。

标签: javascript reactjs flexbox


【解决方案1】:

这有点笨拙,但您可以将ChildDivalign-items: center 居中。

另外,将FullWidthDiv 缩小到 280。 最后,您必须将 flex: 1width: 100% 添加到 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"
    }}
  />
);

如果您希望 FullWidthDiv 具有 100% 的宽度,则必须计算 100% 的宽度并从 MainDiv 的两侧添加填充,它看起来像这样:calc(100% + 2rem)

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2016-05-21
    • 2012-08-24
    • 1970-01-01
    • 2013-03-06
    • 2011-11-19
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多