【问题标题】:Absolute positioned text inside text-wrap div has width and height stuck at 100% of wrap文本换行 div 内的绝对定位文本的宽度和高度停留在 100% 的换行
【发布时间】:2017-07-29 00:27:41
【问题描述】:

我在相对文本换行中有绝对定位的文本,我希望它垂直和水平居中。问题是,文本不会居中,因为它的宽度和高度会自动填充容器。如何解决此问题,以便文本可以在 div 中垂直和水平居中?

JSFiddle

HTML

<div class="text-wrap">
  <h3>Hello</h3>
</div>

CSS

.text-wrap {
  height: 200px;
  width: 120px;
  position: relative;
  border: 1px solid black;
}

.text-wrap h3 {
  position: absolute;
  margin: auto;
  left:0;
  right:0;
  top:0;
  bottom: 0;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    更改绝对元素的CSS规则如下使其居中(将其左上角移动到容器的中心,然后将其向上和向左移动其自身宽度/高度的一半,从而将其居中)

    .text-wrap {
      height: 200px;
      width: 120px;
      position: relative;
      border: 1px solid black;
    }
    
    .text-wrap h3 {
      position: absolute;
      margin: 0;
      padding: 0;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      
    }
    <div class="text-wrap">
      <h3>Hello</h3>
    </div>

    【讨论】:

    • 好的,谢谢。旧浏览器有什么解决办法吗?
    • 几岁? ;-) 好吧,在 真的 旧浏览器中,您可以将容器设置为 table-cell 并将 text-align: centervertical-align: middle 应用于它。 (而不要为内部文本使用容器)
    【解决方案2】:

    试试这个

    .text-wrap {
      height: 200px;
      width: 120px;
      position: relative;
      border: 1px solid black;
    }
    
    .text-wrap h3 {
      margin: 0;
      position: absolute;
      top: 50%;
      left: 50%;
      -ms-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 2012-07-08
      • 1970-01-01
      • 2022-08-18
      • 2021-01-07
      相关资源
      最近更新 更多