html - 如何在 div 中垂直居中 H1?

标签 html css responsive-design

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

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

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

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

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

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实现垂直对齐:

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

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

Example

更新 - CSS3

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

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

Updated fiddle

关于html - 如何在 div 中垂直居中 H1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20562860/

相关文章:

html - Active Scroll 类状态

javascript - 如何将图标放在最右侧的标题中?

css - 有趣的 CSS 响应宽度问题

html - CSS 悬停效果显示另一个 div

html - 如何使用 Bootstrap 4 将列表组变成下拉菜单?

javascript - 针对 iPhone 5 和 5S 的纵向和横向问题

html - CSS 背景图像 url() 在各种浏览器中未显示错误 '404 not found'

html - 超链接的无序列表 - 将元素符号颜色与链接文本颜色匹配

html - Firefox 中奇怪的 float 行为

css - 无法更改 MUI 表填充