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



参考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的容器的大小计算的行的大小垂直居中。这怎么可能?

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

#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;
}
```
<!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>

最新更新