如何居中对齐div中的文本

时间:2015-11-06 13:37:48

标签: html css

我想在此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>

2 个答案:

答案 0 :(得分: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脚本完成,也可以使用position: absolutetop: 0px将div包装在bottom: 0px;样式的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>

答案 1 :(得分:1)

试试这个:

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>

相关问题