【问题标题】:vertical-align middle and text-align center on absolute div在绝对 div 上垂直对齐中间和文本对齐中心
【发布时间】:2014-10-19 02:14:39
【问题描述】:

我有一个具有一定宽度和高度的 div。在那个 div 我也有一个文本。我想将该文本对齐到中心(水平)和中间(垂直)。但是 div 还需要一个position: absolute。所以它可以定位在另一个 div 中。

但是由于absolute,文本将不再垂直对齐。

这就是我所拥有的:

<div style="z-index:20;
    position: absolute;
    border: 1px dotted #16232d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    top:88px; left:31px;
    display: table-cell;
    line-height: normal;
    font-size:32px;
    text-align: center;
    vertical-align: middle;">
   Lorem ipsum dolor sit amet
</div>

示例:http://jsfiddle.net/s8jp5ohh/

文本永远不会包含任何&lt;br&gt;。所以它总是一条线。但是当文本大于 div 的宽度时,它应该自动换行。所以我想保留这个功能(就像你在小提琴中看到的那样)。

有没有办法让文本居中对齐,垂直和水平?

【问题讨论】:

  • 这个问题在stackoverflow.com/questions/2939914/…之前已经回答过
  • 你想要的,单靠css是无法完成的。你能想到的最接近的事情是有一个显示:table 的包装器和你的 div 显示:table-cell。垂直对齐将起作用,水平对齐也是如此。

标签: html css


【解决方案1】:

这将解决它:DEMO

css

.myDiv {
    z-index:20;
    position: absolute;
    border: 1px dotted #16232d;
    width: 300px;
    height: 200px;
    top:88px;
    left:31px;
    line-height: normal;
    font-size:32px;
    text-align: center;
    display: table;
}
.myDiv p {
    display: table-cell;
    vertical-align: middle;
}

html

<div class="myDiv">
    <p>Lorem ipsum dolor </p>
</div>

【讨论】:

    【解决方案2】:

    您必须使用 hack,但它有效:

    JSFiddle.

    HTML

    <div class="block" style="z-index:20;
    position: absolute;
    border: 1px dotted #16232d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    top:88px; left:31px;
    display: table-cell;
    line-height: normal;
    font-size:32px;
    text-align: center;
    vertical-align: middle;">
        <p style="vertical-align: middle; display: inline-block;"> Lorem ipsum dolor sit    amet</p>
    

    CSS:

    .block:before {
        content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
      margin-right: -0.25em;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2017-01-17
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2012-12-09
      • 2017-03-23
      • 2013-06-01
      • 1970-01-01
      相关资源
      最近更新 更多