如何在网格单元内垂直居中放置元素?

时间:2019-01-25 06:40:50

标签: html css

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

我尝试使用“ 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;
}

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

4 个答案:

答案 0 :(得分:1)

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

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

}

答案 1 :(得分:1)

为此,您可以使用line-height:50px,它将相对于父级高度将文本居中。因为高度为50px,所以使用了50px;

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

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

.grid_item span, .grid_item input {
  position: relative;
  vertical-align: middle;
}
<!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>

答案 2 :(得分:1)

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

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

.grid_item span, .grid_item input {
  position: relative;
  vertical-align: middle;
}
<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>

您可以在grid_item上使用display:flex和align-items:center使其居中,希望有帮助

答案 3 :(得分:0)

您可以在constructor(private render: Renderer) { }父级上设置display: flex;,并在.grid_item.grid_item input上将页边距的顶部和底部设置为auto:

.grid_item span