如何根据其他网格项目的大小垂直居中网格项目?

时间:2020-07-20 13:31:16

标签: css css-grid

供参考,index.htmlindex.css

#main-grid {
  display: grid;
  grid-template: [top] 1fr [middle] 2fr [bottom] / [left] 1fr [center] 2fr [right];
}

#main-grid-top-left-item {
  grid-area: top / left / middle / center;
  background-color: red;
}

#main-grid-top-right-item {
  grid-area: top / center / middle / right;
  background-color: lime;
  font-size: xx-large;
}

#main-grid-bottom-left-item {
  grid-area: middle / left / bottom / center;
  background-color: cyan;
}

#main-grid-bottom-right-item {
  grid-area: middle / center / bottom / right;
  background-color: yellow
}

.white-background {
  background-color: white;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="index.css" />
  <title>
    HTML Document
  </title>
</head>

<body>
  <div id="main-grid">
    <div id="main-grid-top-left-item">
      <span class="white-background">
                    0
                </span>
    </div>
    <div id="main-grid-top-right-item">
      <span class="white-background">
                    1
                </span>
    </div>
    <div id="main-grid-bottom-left-item">
      <span class="white-background">
                    2
                </span>
    </div>
    <div id="main-grid-bottom-right-item">
      <span class="white-background">
                    3
                </span>
    </div>
  </div>
</body>

</html>

现在,我想要的是使左上角0相对于使用包含右上角{{ 1}}。那怎么可能?

1 个答案:

答案 0 :(得分:1)

您可以使用良好的旧版flexbox将单元格的内容居中放置:

[ { product_name_en: "product 1", product_id: "1" },
  { product_name_en: "product 2", product_id: "2" },
  { product_name_en: "product 3", product_id: "3"} ]

在您的示例上下文中:

#main-grid-top-left-item {
  grid-area: top / left / middle / center;
  background-color: red;

  // and then...
  display: flex;
  //justify-content: center; // do this if you also want horizontal alignment
  align-items: center;
}
#main-grid {
  display: grid;
  grid-template: [top] 1fr [middle] 2fr [bottom] / [left] 1fr [center] 2fr [right];
}

#main-grid-top-left-item {
  grid-area: top / left / middle / center;
  background-color: red;
  display: flex;
  align-items: center;
}

#main-grid-top-right-item {
  grid-area: top / center / middle / right;
  background-color: lime;
  font-size: xx-large;
}

#main-grid-bottom-left-item {
  grid-area: middle / left / bottom / center;
  background-color: cyan;
}

#main-grid-bottom-right-item {
  grid-area: middle / center / bottom / right;
  background-color: yellow
}

.white-background {
  background-color: white;
}

```