使用CSS网格时,如何在CSS中垂直对齐对象? [英] How to vertically align objects in CSS when working with CSS grids?

查看:96
本文介绍了使用CSS网格时,如何在CSS中垂直对齐对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我知道,对于网格容器,vertical-align没有任何作用.那么解决方案是什么?

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

这个问题被标记为重复,但是,另一个问题问的是水平居中对齐文本,而这里我问的是垂直居中对齐.

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.

推荐答案

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

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

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>

这篇关于使用CSS网格时,如何在CSS中垂直对齐对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆