使用 CSS 网格时如何垂直对齐 CSS 中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45562613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 12:38:34  来源:igfitidea点击:

How to vertically align objects in CSS when working with CSS grids?

csscss-grid

提问by Gesha

I have come across this problem recently. Lets suppose I have a simple <h1>tag and I want to center it vertically, so even when I re-size the window, it will remain in the middle of one of my grid box rows, neglecting its horizontal position.

我最近遇到了这个问题。假设我有一个简单的<h1>标签,我想将它垂直居中,因此即使我重新调整窗口大小,它也会保留在我的网格框行之一的中间,忽略其水平位置。

I know that when it comes to grid containers, vertical-alignhas no effect. So what would be the solution?

我知道当涉及到网格容器时,vertical-align没有任何影响。那么解决方案是什么?

This question has been marked as a duplicate, however, the other question asks about centering text horizontally, whereas, here, I'm asking about vertical centering.

这个问题已被标记为重复,但是,另一个问题询问水平居中文本,而在这里,我询问垂直居中。

采纳答案by Happysmithers

Good question - I managed to work around the issue with a wrapper, and using display: table

好问题 - 我设法用包装器解决了这个问题,并使用 display: table

https://jsfiddle.net/8vjvnznk/

https://jsfiddle.net/8vjvnznk/

.wrapper {
  display: grid;
  grid-template-columns: 100px 100px 300px;
  grid-template-rows: 200px 200px;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
  align-content: space-evenly;
}

.workaround{
  border: 1px solid green;
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: table;
  
}
h1{
  font-size: 1em;
  border: 1px solid yellow;
  display: table-cell;
  vertical-align: middle;
}

#boxc{
 background: red;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 100%;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c" id="boxc">
    <div class="workaround">
      <h1>
        The heading in question!
      </h1>
    </div>
  </div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>

回答by Gesha

There is no need for a table, why you will mix grid with table ?

不需要表格,为什么要混合使用表格和表格?

You can use align-items:centerto achieve vertical centering.

您可以使用align-items:center来实现垂直居中。

If the grid cell is <h1>itself, you can use align-self:centerto vertical center the content into <h1>

如果网格单元格<h1>本身,则可以使用align-self:center将内容垂直居中<h1>