如何在div中垂直居中H1?

问题描述:

首先,我的道歉。我知道这里有这个问题的各种解决方案,但在我的生活,我不能得到任何他们的工作。

First of all, my apologies. I know there are various solutions posted for this issue here, but for the life of me I can't get any of them to work.

对于一个响应式网站,我试图将一个h1置于div中心。

For a responsive website I'm trying to center an h1 in a div.

水平居中不是一个问题,但我遇到垂直居中问题。可能我做错了或误解我在这里发现的解释(或两者)。

Centering horizontally is not an issue, but I'm having problems getting it centered vertically. Presumably I'm doing something wrong or misunderstanding the explanations I found here (or maybe both).

因为我可能解释早期的解决方案,有人请解释一下我必须添加到下面的代码,以获得h1垂直中心?

So as I'm probably interpreting earlier solutions given the wrong way, could someone please explain what exactly I have to add to the code beneath to get the h1 to center vertically?

(为了使这个问题与尽可能多的人相关,我已经删除了我之前尝试的所有代码。)

(To make this question relevant to as much people as possible, I've already stripped the code of all my previous attempts to do so myself.)

CSS:

html, body {
height: 100%;
margin: 0;
}

#section1 {
min-height: 90%; 
text-align:center
}

HTML:

<div class="section" id="section1">
<h1>Lorem ipsum</h1>
</div> 


> display:table-cell :

you can achieve vertical aligning with display:table-cell:

#section1 {
    height: 90%; 
    text-align:center; 
    display:table;
    width:100%;
}

#section1 h1 {display:table-cell; vertical-align:middle}

示例

更新 - CSS3

方法到垂直对齐,您可以使用以下css 3,它应该在所有最新的浏览器中支持:

For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:

#section1 {
    height: 90%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

更新了小提琴