简体   繁体   English

文本换行div中的绝对定位文本的宽度和高度停留在换行的100%

[英]Absolute positioned text inside text-wrap div has width and height stuck at 100% of wrap

I have absolute positioned text inside a relative text wrap and I want it to vertically and horizontally center. 我在相对文本换行中放置了绝对定位的文本,我希望它在垂直和水平方向居中。 The issue is, the text won't center because it's width and height automatically fill the container. 问题是,文本不会居中,因为它的宽度和高度会自动填充容器。 How do I fix this so the text can be centered in the div, both vertically and horizontally? 如何解决此问题,使文本可以在div中居中居中(垂直和水平)?

JSFiddle JSFiddle

HTML 的HTML

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

CSS 的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;
}

Change the CSS rule for the absolute element as follows to center it (moves its upper left corner to the center of the container, then moves it back up and left by half of its own width/height, thereby centering it) 如下更改绝对元素的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> 

Try this 尝试这个

.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%);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM