如何在 div 中垂直居中 H1?
Posted
技术标签:
【中文标题】如何在 div 中垂直居中 H1?【英文标题】:How do I vertically center an H1 in a div? 【发布时间】:2014-01-01 00:09:54 【问题描述】:首先,我很抱歉。我知道这里有针对这个问题发布的各种解决方案,但在我的一生中,我无法让它们中的任何一个起作用。
对于响应式网站,我尝试将 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>
【问题讨论】:
去掉h1
padding
和 margin
并在 div
上使用 vertical-align
。
@MelanciaUK 那行不通。
将行高设置为 1.2
@NiettheDarkAbsol 是的,我刚刚在小提琴上试过。不好的评论。哈哈
查看此链接***.com/questions/6254793/…
【参考方案1】:
你可以用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
【讨论】:
不错!对齐项目:居中;是我正在寻找的垂直对齐方式。谢谢。 感谢 CSS3 替代品! 在我的场景中没有任何效果。这正是我正在寻找的。非常感谢!【参考方案2】:您可以使用display
属性实现此目的:
html, body
height:100%;
margin:0;
padding:0;
#section1
width:100%; /*full width*/
min-height:90%;
text-align:center;
display:table; /*acts like a table*/
h1
margin:0;
padding:0;
vertical-align:middle; /*middle centred*/
display:table-cell; /*acts like a table cell*/
演示:http://jsfiddle.net/a3Kns/
【讨论】:
干杯!使用 Pete 的解决方案,但本质上这是相同的。感谢您的帮助!【参考方案3】:我已经成功地将文本放入跨度标记中,然后在该跨度上设置垂直对齐:中间。不知道这是如何跨浏览器兼容的,我只在 webkit 浏览器中测试过。
【讨论】:
谢谢!假设这也应该起作用。接受的答案会帮助您确保其跨浏览器兼容吗? 回头看我的代码,其实挺hacky的,所以上面table
的回答比较好。我的方法需要一个额外的跨度设置为width: 0;
。但是,如果您或其他人有兴趣,请参阅 jsfiddle here【参考方案4】:
HTML
<div id='sample'>
<span class='vertical'>Test Message</span>
</div>
CSS
#sample
height:100px;
width:100%;
background-color:#003366;
display:table;
text-align: center;
.vertical
color:white;
display:table-cell;
vertical-align:middle;
小提琴:Demo
【讨论】:
【参考方案5】:只需使用上下内边距,它会自动将内容垂直居中。
【讨论】:
【参考方案6】:Flexbox 是一种在 div 中居中放置 h1 标签的可靠方法。
<div class="section" id="section1">
<h1>Lorem ipsum</h1>
</div>
这是 OP:s HTML。让我们保持这种状态。 现在使用 CSS,我们可以添加 display flex 和一些属性。这是一个工作代码 sn-p,它显示了 flexbox 如何进行垂直对齐。
#root
width: 90vw;
height: 90vh;
border: 2px solid green;
#section1
display: flex;
flex-direction: row;
flex: 1;
min-height: 90%;
border: 2px solid red;
background-color: orange;
text-align: center;
/* this does align h1 if h1 is wider than its containing text */
#section1>h1
flex: 1;
/* this makes the h1 take all available width in its containing div, and makes text-align: center property work inside section1 */
background-color: #666333;
align-self: center/* this is finally the property that vertically aligns the h1 title inside its containing div */
<!DOCTYPE html>
<html>
<header>Demo</header>
<div id="root">
<div id="section1">
<h1>Title Centered</h1>
</div>
</div>
</html>
由于接受的答案的 CSS3 选项垂直对齐包含的 div 而不是 h1 标记,因此此答案显示了 h1 如何在预先确定的、更大的包含 div 内垂直对齐。
【讨论】:
以上是关于如何在 div 中垂直居中 H1?的主要内容,如果未能解决你的问题,请参考以下文章