问题
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.
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.
回答1:
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>
回答2:
There is no need for a table, why you will mix grid with table ?
You can use align-items:center
to achieve vertical centering.
If the grid cell is <h1>
itself, you can use align-self:center
to vertical center the content into <h1>
来源:https://stackoverflow.com/questions/45562613/how-to-vertically-align-objects-in-css-when-working-with-css-grids