【问题标题】:How to control the divs display in flex box如何控制 div 在弹性框中的显示
【发布时间】:2021-05-09 05:57:45
【问题描述】:

我正在制作一个博客应用程序,你可以在这里看到它。 https://6t61y.csb.app/(源码点击底部沙箱按钮)

我想像this 设计一样一次显示 2 张卡片,并在其下方再显示 2 张卡片。如何做到这一点?

我阅读了几篇类似的帖子,但对我没有任何帮助。 (这可能是一些类似帖子的副本)。对于此类问题,是否有任何要记住的经验法则,因为我作为初学者经常遇到这个问题?

注意:我没有使用任何外部 UI 库,例如材料 UI 的引导程序。所以我不能使用 Grid item sm=6 sm=6 这种技术。

【问题讨论】:

  • 如果您想要这里的答案,请在这里提出足够多的问题,以便为您的问题提供有用的答案。

标签: css flexbox breakpoints


【解决方案1】:

我分叉了您的沙盒并创建了自己的沙盒,成功创建了您想要的设计。你可以看到它here

之所以可行,是因为在子元素中,我放了:

flex: 1 0 40%;

这是以下属性的简写:

flex-grow: 1;
flex-shrink: 0;
flex-basis: 40%;

我将 flex-basis 设置为 40% 的原因是考虑到您要添加的 2vh 的边距。如果没有该边距,它可以设置为 50%,但它们会紧挨着彼此卡住。这个数字可以根据您和您网站的需要增加或减少。

Here 是我强烈推荐给您继续学习 flexbox 的资源。它非常全面,并解释了每一个属性(我与这个网站完全没有任何关系,它只是教会了我几乎所有关于 flexbox 的知识)。

【讨论】:

  • 非常感谢!我一定会阅读提供的资源。
【解决方案2】:

您可以在 CSS 中使用 grid 并使用 grid-template-columns: repeat(2, 1fr)grid-template-columns: 1fr 1fr 分为 2 列

.parent {
  margin: 4rem;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

.child {
  height: 300px;
  background-color: blueviolet;
}
<div class="parent">
  <div class="child"> Card </div>
  <div class="child"> Card </div>
  <div class="child"> Card </div>
  <div class="child"> Card </div>
</div>

【讨论】:

    【解决方案3】:

    您可能没有使用 boottrap 或 material-ui 等,但您也可以创建一个简单的可重用组件。

    import React, { useMemo } from "react";
    const Grid = ({ container, item, children, ...props }) => {
      const size = useMemo(() => {
        switch (props.size) {
          case 2:
            return "50%";
          case 3:
            return "33.3333%";
          default:
            return "100%";
        }
      }, [props]);
    
      if (container) {
        return (
          <div style={{ display: "flex", maxWidth: "100%", flexWrap: "wrap" }}>
            {children}
          </div>
        );
      }
    
      if (item) {
        return (
          <div style={{ display: "flex", flexBasis: size, maxWidth: size }}>
            {children}
          </div>
        );
      }
    
      return null;
    };
    
    export default Grid;
    

    然后像这样使用它

        <Grid container>
            <Grid item> 
              <Card />
            </Grid>      
            <Grid item size={2}>
              <Card />
            </Grid>
            <Grid item size={2}>
              <Card />
            </Grid>
            <Grid item size={3}>
              <Card />
            </Grid>
            <Grid item size={3}>
              <Card />
            </Grid>
            <Grid item size={3}>
              <Card />
            </Grid>
          </Grid>
    

    代码沙盒:https://codesandbox.io/s/admiring-dewdney-stbq0?file=/src/App.js

    注意:您可以用 CSS 替换样式。 注意:将您的卡片 css 宽度更改为“100%”;

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多