簡體   English   中英

如何 position 子 div 從父 div 的開頭跨越到結尾?

[英]How to position a child div to span from the beginning to the end of a parent div?

我正在嘗試 position 將FullWidthDiv組件從MainDiv端的開頭跨越到結尾。 我試過放棄絕對的 position 並玩弄 flex,但我不能讓它不從SubDiv組件開始。

有可能實現這一目標嗎?

我的CodeSandbox方法。

是我想要實現的目標

這有點 hacky,但您可以使用align-items: center ChildDiv居中。

此外,將FullWidthDiv縮小到 280。最后,您必須將flex: 1 , width: 100%添加到 div 中,將SubChildDivApp組件中。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM