【问题标题】:center a text inside a div [duplicate]在 div 中居中文本 [重复]
【发布时间】:2015-12-05 11:29:54
【问题描述】:

我想知道如何在 div 中将文本居中。在我的代码中,这不适用于每个 p-tag,因为文本长度不一样。

HTML:-

<div class="textBlock">
  <p>text text text</p>
</div>

CSS:-

#content .textBlock {
 position: relative;
 text-align: center;
 width: 100%;
 float: left;
 display: block;
 min-height: 160px;
}

#content .textBlock p {
 position: absolute;
 top: 50%;
 -webkit-transform: translateY(-50%);
 -ms-transform: translateY(-50%);
 transform: translateY(-50%);
 font-size: 28px;
 font-family: Helvetica, Arial;
 font-weight: 100;
 padding: 0 5%;
 line-height: 34px;
 letter-spacing: 0.1em; 
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果您只是对齐文本,不确定所有其他代码的用途?

    .textBlock {
     text-align: center;
     min-height: 160px;
    }
    
    .textBlock p {
     font-size: 28px;
     font-family: Helvetica, Arial;
     line-height: 34px;
     letter-spacing: 0.1em; 
    }
    <div class="textBlock">
      <p>text text text</p>
    </div>

    【讨论】:

    • 没错,就是绝对定位导致了问题。不确定这是否是答案;如果 OP 确实需要绝对定位怎么办?
    【解决方案2】:

    请试试这个:

    HTML:

    <div class="textBlock">
      <p>text text text</p>
    </div>
    

    CSS:

    .textBlock {
     text-align: center;
    
        background-color:gray;
    }
    
    .textBlock p {
     font-size: 28px;
     font-family: Helvetica, Arial;
     line-height: 34px;
     letter-spacing: 0.1em; 
        color:white;
    }
    

    DEMO

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 2018-05-20
      • 2018-02-04
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2014-12-25
      相关资源
      最近更新 更多