【问题标题】:2x2 Grid equal height despite box content amount2x2 网格等高,尽管盒子内容量很大
【发布时间】:2017-12-17 10:12:22
【问题描述】:

我正在尝试创建一个 2x2 网格,其中四个单独的框(红色、蓝色、绿色、黄色)的高度都相等,尽管它们包含多少内容。

#rowTwo {
  background-color: pink;
  min-height: 25%;
  display: flex;
  flex-direction: column; 
  align-items: center;
}

#grid2x2 {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background-color: orange;
  width: 80%;
  justify-content: center;
}

.box {
  display: flex;
  flex-basis: calc(50% - 20px);
  margin: 5px;
  justify-content: center;
  padding-top: 5%;
  overflow: hidden;
}
<div id={styles.rowTwo}>
  <Heading title="My Title"/>
  <div id={styles.grid2x2}>
    <div id={styles.boxOne} className={styles.box}>
        <DescriptionBoxItemWithHeading item={this.state.sectionTwoItems[0]}/>
    </div>
    <div id={styles.boxTwo} className={styles.box}>
        <DescriptionBoxItemWithHeading item={this.state.sectionTwoItems[1]}/>
    </div>
    <div id={styles.boxThree} className={styles.box}>
        <DescriptionBoxItemWithHeading item={this.state.sectionTwoItems[2]}/>
    </div>
    <div id={styles.boxFour} className={styles.box}>
        <DescriptionBoxItemWithHeading item={this.state.sectionTwoItems[3]}/>
    </div>
  </div>
</div>

我面临的问题是一个盒子会展开到一行中最大内容的高度。

这是概述我的问题的图片:

有人知道我是如何做到这一点的吗?

【问题讨论】:

  • 请提供最终生成的不带任何动态模板代码的 HTML...
  • 这对于 flexbox 是不可能的。它只能在一个方向上均衡尺寸。您可以拥有相等的高度(以行为单位)或宽度(以列为单位),但不能同时拥有两者。你需要 JS。
  • 溢出-y:自动?
  • @Paulie_D 我如何使用 JS 来实现这一点?谢谢

标签: html css reactjs flexbox


【解决方案1】:

您可以在 CSS 中执行此操作,方法是使用 padding-top 添加高度,然后使用绝对定位在此填充顶部绘制您的内容。

这里是一个例子:https://codepen.io/anon/pen/xpwooz

#grid2x2 {
    display: flex;
    flex-wrap: wrap;
    background-color: orange;
}

.box {
    display: flex;
    flex-basis: calc(50% - 20px);
    margin: 5px;
    justify-content: center;
    overflow: hidden;
    background: red;
    padding-top: 100px;
    position: relative;
}

.content {
  position: absolute;
  background: green;
  top: 0;
  width: 100%;
}    

问题是您不能根据内容高度动态更改此高度。您可以将其设置为固定大小或将其设置为百分比并根据其父宽度更改大小。如果你想根据最大的内容元素改变高度,我认为你需要使用 javascript。

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2016-03-26
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多