在CSS网格中垂直对齐内容

时间:2018-05-24 19:55:17

标签: html css css3 centering

我下面有一个CSS网格,我希望内容(现在的字母)在单元格内垂直对齐。实现这一目标的最佳方法是什么?单元格上的vertical-align:middle似乎没有做任何事情,网格容器上的align-items:center;工作,但是高度都不同。

body {
  margin: 40px;
}

.wrapper {
		display: grid;
    grid-gap: 10px;
		grid-template-columns: [col] 100px [col] 100px [col] 100px;
		grid-template-rows: [row] auto [row] auto [row] ;
		background-color: #fff;
		color: #444;
	}

	.box {
		background-color:#444;
		color:#fff;
		padding:20px;
		font-size:150%;
	}

	.a {
		grid-column: col / span 2;
		grid-row: row 1 / 3;
	}
	.b {
		grid-column: col 3 / span 1;
		grid-row: row ;
	}
	.c {
		grid-column: col 3 / span 1;
		grid-row: row 2 ;
	}
	.d {
		grid-column: col / span 1;
		grid-row: row 3;
	}

	.e {
		grid-column: col 2 / span 1;
		grid-row: row 3;
	}

.f {
  grid-column: col 3 / span 1;
  grid-row: row 3;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>

1 个答案:

答案 0 :(得分:5)

如果您只想让它们垂直居中,可以将S1 : "0123412315", S2 : "324153243", S3 : "12354244", S[n] : "......." display:flex;添加到框类中:

&#13;
&#13;
align-items: center;
&#13;
body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: [col] 100px [col] 100px [col] 100px;
  grid-template-rows: [row] auto [row] auto [row];
  background-color: #fff;
  color: #444;
}

.box {
  background-color: #444;
  color: #fff;
  padding: 20px;
  font-size: 150%;
  display: flex;
  align-items: center;
}

.a {
  grid-column: col / span 2;
  grid-row: row 1 / 3;
}

.b {
  grid-column: col 3 / span 1;
  grid-row: row;
}

.c {
  grid-column: col 3 / span 1;
  grid-row: row 2;
}

.d {
  grid-column: col / span 1;
  grid-row: row 3;
}

.e {
  grid-column: col 2 / span 1;
  grid-row: row 3;
}

.f {
  grid-column: col 3 / span 1;
  grid-row: row 3;
}
&#13;
&#13;
&#13;