首页 > 解决方案 > CSS Grid 中的 Chrome / Firefox 百分比高度差异

问题描述

请注意,以下问题可以通过使用 fr 单位而不是 % 和 auto 来解决,但我正在寻找关于为什么首先出现问题的解释。

在我下面的代码中,

Firefox:不遵守grid-template-rows. 对每一行应用相等的高度,但网格项不会溢出容器。

Chrome:似乎服从该grid-template-rows属性,但网格项溢出容器。

最初我认为问题出在%上,但它是行的允许单位。我将自动值换成了10%,但这产生了它自己的问题。

我查看了文档,但我遗漏了一些东西。

有人有一个直截了当的解释吗?

body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 30% 30% 30%;
  grid-template-rows: 30% auto 60%;
  background-color: #f00;
  color: #444;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
}
<div class="wrapper">
  <div class="box">A</div>
  <div class="box">B</div>
  <div class="box">C</div>
  <div class="box">D</div>
  <div class="box">E</div>
  <div class="box">F</div>
  <div class="box">G</div>
  <div class="box">H</div>
  <div class="box">I</div>
</div>

密码笔

标签: cssgoogle-chromefirefoxcss-grid

解决方案


最初我认为问题出在%上,但它是行的允许单位。我将自动值换成了10%,但这产生了它自己的问题。有人有一个直截了当的解释吗?

问题实际上是%单位的使用。

直截了当的解释是,当父容器上没有定义或继承的长度时,不同浏览器对百分比长度的处理方式不同。

因此,由于网格容器没有定义高度,浏览器会不一致地呈现以百分比定义的行高。

这些变化在这些帖子中进行了详细探讨:

简单的解决方案是在容器上定义一个高度。在下面的示例中,我添加height: 300px.wrapper. 现在,这些行在浏览器中呈现相同。

.wrapper {
  height: 300px; /* new */
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 30% 30% 30%;
  grid-template-rows: 30% auto 60%;
  background-color: #f00;
  color: #444;
}

.box {
  background-color: lightblue;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
}
<div class="wrapper">
  <div class="box">A</div>
  <div class="box">B</div>
  <div class="box">C</div>
  <div class="box">D</div>
  <div class="box">E</div>
  <div class="box">F</div>
  <div class="box">G</div>
  <div class="box">H</div>
  <div class="box">I</div>
</div>


推荐阅读