【问题标题】:How to center align text in div [duplicate]如何在div中居中对齐文本[重复]
【发布时间】:2015-11-06 13:37:47
【问题描述】:

我想在这个 div 内垂直和水平居中对齐文本。所以它的上下填充相同。

如何使用我当前的代码执行此操作?我的小提琴:http://jsfiddle.net/hr2aLrc0/

<div style="height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">
    
    <h1>Your Title</h1>
    <p>Title<br />Description</p>
    
</div>

【问题讨论】:

  • 正确的垂直对齐是 CSS 长期缺失的特性之一。有关解决方法,请参阅 this page

标签: html css


【解决方案1】:

这是一个标准问题,所以怀疑没有重复。 ;-)

text-align: center;扩展你的风格/课程

<div style="text-align: center; height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">

    <h1>Your Title</h1>
    <p>Title<br />Description</p>

</div>

垂直对齐没那么容易。

这可以使用 java 脚本来完成,或者如果您将 div 包装在带有 top: 0pxbottom: 0px;position: absolute 样式的 div 中。然后您可以使用margin-top: auto; margin-bottom: auto; height: ???px 将内部 div 居中。

<div style="position: absolute; top: 0; bottom: 0; left:0; right:0; height: auto; width: auto;">
  <div style="margin-top: auto; margin-bottom:auto; text-align: center; height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">

    <h1>Your Title</h1>
    <p>Title<br />Description</p>

  </div>
</div>

【讨论】:

  • 副本中的要点。我发现这看起来更像我需要的:jsfiddle.net/CtH9k
  • 是的,这个小提琴也可以。但我不确定它是否适用于 H1 标签。但这是可能的,这将是一个很好的解决方案。我已经编辑了我的答案以向您展示另一种方式。
【解决方案2】:

试试这个:

div {
  width: 250px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
<div style="height:300px;background:url('http://placehold.it/600x300') 0 0 no-repeat;background-size:cover">
    
    <h1>Your Title</h1>
    <p>Title<br />Description</p>
    
</div>

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 2011-02-11
    • 2018-10-18
    • 2018-10-29
    • 2016-09-21
    • 2017-10-17
    • 2016-02-13
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多