Chrome / Firefox percentage height differences in CSS Grid

前端 未结 2 1866
北荒
北荒 2020-12-19 23:22

Please note, the following problem can be solved by using fr units instead of % and auto, but I am looking for an explanation as to why the problem occurs in the first place

2条回答
  •  半阙折子戏
    2020-12-19 23:27

    Initially I thought the issue was with % but it is an allowable unit for the row. I swapped out the auto value for 10% but that created its own problem. Anyone have a straight-forward explanation?

    The problem actually is the use of % units.

    The straightforward explanation is that percentage lengths are processed differently across browsers when there is no defined or inherited length on the parent container.

    Therefore, because the grid container has no defined height, browsers will render the row heights, which are defined with percentages, inconsistently.

    These variations are explored in detail in these posts:

    • Chrome / Safari not filling 100% height of flex parent
    • Working with the CSS height property and percentage values

    The simple solution is to define a height on the container. In my example below, I've added height: 300px to .wrapper. Now the rows render the same across browsers.

    .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;
    }
    A
    B
    C
    D
    E
    F
    G
    H
    I

提交回复
热议问题