首页 > 解决方案 > 如何在网格单元格中垂直居中元素?

问题描述

所以我试图在网格单元格中垂直对齐一个和元素。想知道是否有任何方法可以在不使用填充的情况下做到这一点,因为无论网格单元的大小如何,我都是要居中的元素

我试过使用“vertical-align:middle”,但这似乎没有任何作用

HTML:

<!DOCTYPE html>
<html>
  <head>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div class = "grid">
      <label class = "grid_item">
        <input type = "checkbox" name = "check">
        <span>text</span>
      </label>
      <label class = "grid_item">
        <input type = "checkbox" name = "check">
        <span>text</span>
      </label>
    </div>
  </body>
</html>

CSS:

.grid {
  display: grid;
  border-top: 1px black solid;
}

.grid_item {
  border: 1px black solid;
  border-top: none;
  height: 50px;
}

.grid_item span, .grid_item input {
  position: relative;
  vertical-align: middle;
}

我希望这会使元素垂直居中,但似乎没有效果

标签: htmlcss

解决方案


尝试使用 display flex 属性来对齐项目

.grid_item {
border: 1px black solid;
border-top: none;
height: 50px;
display: flex;
align-items: center;

}


推荐阅读