看看这个codepen:
https://codepen.io/rachelandrew/pen/WQNqKy
body {
margin: 40px;
font: 80% Arial, Helvetica, sans-serif;
}
.wrapper {
display: grid;
align-items: center;
background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
grid-gap: 10px;
grid-template-columns: repeat(6, 150px);
grid-template-rows: repeat( 4, 150px);
background-color: #fff;
color: #444;
}
.box {
border: 1px solid #444;
padding: 20px;
font-size: 150%;
}
.a {
grid-column: 1 / 3;
grid-row: 1 / 3;
}
.b {
grid-column: 3 / 5;
grid-row: 1 / 3;
}
.c {
grid-column: 1 / 3;
grid-row: 3 / 6;
}
.d {
grid-column: 3 / 5;
grid-row: 3 / 6;
}
.e {
grid-column: 5 / 7;
grid-row: 1 / 6;
align-self: stretch;
}

<div class="wrapper">
<div class="box a">
<p>This is box A. </p>
</div>
<div class="box b">
<p>This is box B.</p>
</div>
<div class="box c">
<p>This is box C.</p>
</div>
<div class="box d">
<p>This is box D.</p>
</div>
<div class="box e">
<p>Each of the boxes on the left has a grid area of 3 columns and 3 rows (we're counting the gutter col/row). </p>
<p>The align-items property is used to align the content inside each grid-area.</p>
<p>Other values of align-items are:</p>
<ul>
<li>stretch</li>
<li>start</li>
<li>end</li>
<li>center</li>
</ul>
</div>
</div>
&#13;
这
https://gridbyexample.com/examples/example24/
元素a
有以下规则:
.a {
grid-column: 1 / 3;
grid-row: 1 / 3;
}
没有align-items: center;
它取前两个方格(x,y)
如规则所述,但如果我应用规则
align-items: center
给父母
尺寸变小。
有人可以解释原因吗?
答案 0 :(得分:1)
网格容器的HTML结构由三个级别组成:
每个级别代表一个单独的元素。
将align-items: center
应用于容器时,它将应用于网格项。这正是您的代码示例中发生的事情。
如果您希望网格项的内容居中,那么您不会从主容器中定位它(2级以上)。您从网格项(父项)中定位它。
您可以使用嵌套网格甚至弹性容器来居中文本。
.wrapper {
display: grid;
/* align-items: center; */
grid-gap: 10px;
grid-template-columns: repeat(6, 150px);
grid-template-rows: repeat( 4, 150px);
}
.box {
display: flex; /* new */
align-items: center; /* new; vertical alignment */
justify-content: center; /* new (and optional); horizontal alignment */
}
body {
margin: 40px;
font: 80% Arial, Helvetica, sans-serif;
}
.wrapper {
display: grid;
/* align-items: center; */
background: no-repeat url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/12005/grid.png);
grid-gap: 10px;
grid-template-columns: repeat(6, 150px);
grid-template-rows: repeat( 4, 150px);
background-color: #fff;
color: #444;
}
.box {
border: 1px solid #444;
padding: 20px;
font-size: 150%;
display: flex;
align-items: center;
justify-content: center;
/* optional */
}
.a {
grid-column: 1 / 3;
grid-row: 1 / 3;
}
.b {
grid-column: 3 / 5;
grid-row: 1 / 3;
}
.c {
grid-column: 1 / 3;
grid-row: 3 / 6;
}
.d {
grid-column: 3 / 5;
grid-row: 3 / 6;
}
.e {
grid-column: 5 / 7;
grid-row: 1 / 6;
align-self: stretch;
}
<div class="wrapper">
<div class="box a">
<p>This is box A. </p>
</div>
<div class="box b">
<p>This is box B.</p>
</div>
<div class="box c">
<p>This is box C.</p>
</div>
<div class="box d">
<p>This is box D.</p>
</div>
</div>
此处有更多详情:Centering in CSS Grid