如何在 div 中垂直居中 H1? [英] How do I vertically center an H1 in a div?

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

问题描述

首先,我很抱歉.我知道这里发布了针对此问题的各种解决方案,但在我的一生中,我无法让其中任何一个发挥作用.

对于响应式网站,我试图将 h1 置于 div 中.

水平居中不是问题,但我在使其垂直居中时遇到问题.大概是我做错了什么或者误解了我在这里找到的解释(或者两者都有).

因此,由于我可能以错误的方式解释了早期的解决方案,有人可以解释一下我必须在下面的代码中添加什么才能使 h1 垂直居中吗?

(为了使这个问题与尽可能多的人相关,我已经剥离了我自己以前尝试这样做的所有代码.)

CSS:

html, body {高度:100%;边距:0;}#section1 {最小高度:90%;文本对齐:居中}

HTML:

<h1>Lorem ipsum</h1>

解决方案

可以通过display:table-cell实现垂直对齐:

#section1 {高度:90%;文字对齐:居中;显示:表;宽度:100%;}#section1 h1 {display:table-cell;垂直对齐:中间}

示例

更新 - CSS3

对于垂直对齐的替代方法,您可以使用以下所有最新浏览器都应支持的 css 3:

#section1 {高度:90%;宽度:100%;显示:弹性;对齐项目:居中;对齐内容:居中;}

更新小提琴

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.

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).

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> 

解决方案

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}

Example

Update - CSS3

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;
}

Updated fiddle

这篇关于如何在 div 中垂直居中 H1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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