【问题标题】:css - using grid-auto-column to create dynamic widthscss - 使用 grid-auto-column 创建动态宽度
【发布时间】:2019-05-16 22:29:09
【问题描述】:

我试图让我的 css 网格要么是每行 2 个块(如果有足够的项目),要么是一个跨越整个宽度的块。但是,我似乎无法使用 grid-auto-column 让它工作。

顶部块是我想要的样子,底部块是我当前的 css 正在创建的。

.flex1 {
  display: flex;
  flex-direction: row;
  flex: 1;
}

.grid1 {
  display: grid;
  grid-auto-columns: minmax(50%, 100%);
}

div.height {
  height: 50px;
  width: 100%;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<div class="flex1">
  <div class="red height">
  </div>
  <div class="blue height">
  </div>
</div>
<div>
  <div class="green height">
  </div>
</div>

<br><br>

<div class="grid">
  <div class="red height">
  </div>
  <div class="blue height">
  </div>
  <div class="green height">
  </div>  
</div>

【问题讨论】:

  • 在 css 中使用 .grid1,在 html 中使用 class="grid"

标签: html css flexbox css-grid


【解决方案1】:

不幸的是,据我所知,Grid 无法做到这一点,但对于 Flexbox 来说,这是一项完美而简单的工作,因为您只需要处理one单维布局,在您的情况下为 rows

下面我为您提供 flex-items 所需结果/行为的较短版本,标记和样式更少:

.flex {
  display: flex;
  flex-wrap: wrap; /* enables wrapping of flex-items */
}

.flex > div {
  flex: 1 0 50%; /* grows full width if alone in a row / doesn't shrink / initial width set to 50%, i.e. can't be less than 50% of the parent's width */
  height: 50px;
}

.red {background: red}
.blue {background: blue}
.green {background: green}
.yellow {background: yellow}
<div class="flex">
  <div class="red"></div>
</div>
<br>
<div class="flex">
  <div class="red"></div>
  <div class="blue"></div>
</div>
<br>
<div class="flex">
  <div class="red"></div>
  <div class="blue"></div>
  <div class="green"></div>
</div>
<br>
<div class="flex">
  <div class="red"></div>
  <div class="blue"></div>
  <div class="green"></div>
  <div class="yellow"></div>
</div>

【讨论】:

  • 好的,这是一个很好的答案,那时不需要专门的网格。
  • Ty,确切地说,在你的情况下不需要网格。
【解决方案2】:

使用grid-template-areas: "a b" "c c";(在html中将.grid1更改为.grid

还将grid-area:; 设置为.grid 内的每个div

.flex1 {
  display: flex;
  flex-direction: row;
  flex: 1;
}

.grid {
  display: grid;
  grid-auto-columns: minmax(50%, 100%);
  grid-template-areas: "a b" "c c";
}

div.height {
  height: 50px;
  width: 100%;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<div class="flex1">
  <div class="red height">
  </div>
  <div class="blue height">
  </div>
</div>
<div>
  <div class="green height">
  </div>
</div>

<br><br>

<div class="grid">
  <div class="red height" style="grid-area: a;">
  </div>
  <div class="blue height" style="grid-area: b;">
  </div>
  <div class="green height" style="grid-area: c;">
  </div>  
</div>

【讨论】:

  • 我需要将绿色块拉伸到 100%,因为它是该行的唯一块
  • 我想这是目前可用的解决方法。但是我想更具体地说明自动列,因为如果我有可变数量的项目,比如可能是 3 到 10 个项目,那么我将如何做到这一点,以便它自动生成它?
  • 这是我建议您使用flex 而不是grid 的原因之一
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2013-07-25
  • 2012-04-09
  • 1970-01-01
  • 2021-02-20
相关资源
最近更新 更多