【问题标题】:Why does grid area shrink other cells, even if it has enough space?为什么网格区域会缩小其他单元格,即使它有足够的空间?
【发布时间】:2020-03-28 09:16:57
【问题描述】:

我有一个非常简单的网格,带有标题和两列。网格有一个固定的宽度:300px,而旁边也有一个固定的宽度:100px

如果我增加标题的min-width200px 更多,那么aside 部分会缩小。

为什么?据说,它可以增长到两列的宽度,而不改变其他列的宽度。

.container {
  width: 300px;
  display: grid;
  grid-template-columns: minmax(0, max-content) auto;
  grid-template-rows: max-content auto;
  grid-template-areas: "header header"
    "aside main";
}
header {
  grid-area: header;
  background-color: lightblue;
  min-width: 250px;
  /* Why if min-width > 200, then the aside shrinks?? */
}
aside {
  grid-area: aside;
  background-color: lightgreen;
  width: 100px;
}
main {
  grid-area: main;
  background-color: lightpink;
}
<section class="container">
  <header>
    Header
  </header>

  <aside>
    Aside
  </aside>

  <main>
    Main
  </main>
</section>

JSFiddle:https://jsfiddle.net/a1zto75g/

【问题讨论】:

标签: html css css-grid


【解决方案1】:

这是minmax()max-content 和网格项目宽度之间的复杂交互。

考虑在容器级别管理所有大小。

.container {
  height: 100vh;
  width: 300px;
  display: grid;
  grid-template-columns: 100px 1fr; /* adjustment */
  grid-template-rows: auto 1fr;     /* adjustment */
  grid-template-areas: " header header " 
                        " aside main ";
}

header {
  grid-area: header;
  background-color: lightblue;
}

aside {
  grid-area: aside;
  background-color: lightgreen;
}

main {
  grid-area: main;
  background-color: lightpink;
}

body {
  margin: 0;
}
<section class="container">
  <header>Header</header>
  <aside>Aside</aside>
  <main>Main</main>
</section>

jsFiddle demo

【讨论】:

  • 我必须使用minmax,因为侧面的实际宽度未知。
  • 然后使用auto
  • 谢谢。对于我的特殊情况,这是一个很好的解决方案,但我也想了解这种行为。
  • grid-template-columns: minmax(auto, min-content) 1fr; 是我的特殊情况的最佳解决方案。 jsfiddle.net/9xjc3451
【解决方案2】:

我有一个解决方法:将order: 1; 放在一边。然后,网格计算其他部分的width,然后正确放置一边。

很奇怪。

html,
body,
.container {
  height: 100%;
  margin: 0;
}

.container {
  width: 300px;
  display: grid;
  grid-template-columns: minmax(0, 100px) auto;
  grid-template-rows: 30px auto;
  grid-template-areas: "header header" "aside main";
}

header {
  grid-area: header;
  background-color: lightblue;
  min-width: 250px;
  /* Why if min-width > 200, then the aside shrinks?? */
}

aside {
  order: 1;
  /* THIS IS THE WORKOROUND */
  grid-area: aside;
  background-color: lightgreen;
  width: 100px;
}

main {
  grid-area: main;
  background-color: lightpink;
}
<section class="container">
  <header>
    Header
  </header>

  <aside>
    Aside
  </aside>

  <main>
    Main
  </main>
</section>

【讨论】:

  • 你有一个溢出,我们看不到主要元素
  • 嗯...你是对的。这是同样的怪事。为什么标题的min-width 会影响主要部分的宽度?!
  • 背后有一个复杂的逻辑,仍然没有拼图的所有部分。当我这样做时,我会写一个答案......作为旁注,你在最初的例子中也有溢出。将 z-index 添加到一边,您将获得与 order 相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 2022-09-28
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多