CSS : centering absolute positioned text inside relative parent

∥☆過路亽.° 提交于 2019-12-04 08:30:56

问题


How can I center absolute positioned text inside fluid relative parent? I'm trying to use text-align:center on parent elements but it always centers child's left corner, not element itself.

http://jsfiddle.net/sucTG/2/


回答1:


The thing is that position:absolute; modifies the element's width to fit its content, and that text-align: center; centers the text within the element block's width. So if you add a position: absolute; don't forget to increase the width of the element, or else the text-align: center; property will be useless.

The best way to solve this is to add a width: 100%; and a left: 0px; in the .text section.

http://jsfiddle.net/27van/




回答2:


Update: What I put before was bad/wrong

http://jsfiddle.net/brJky/1/

This should be MUCH closer to what you want?

Your text is relative and your other elements inside the container are absolute!

.text {
    color:#fff;
    padding:50px 0;
    display:block;
    position:relative;
}

.absolute {
    background:#f0f;
    height:25px; width:25px;
    position:absolute;
    top:36px; left:50%;
}



回答3:


You can now achieve what you want more elegantly with flex. See for example:

HTML:

<div class="container">
  <div class="text">Your text</div>
</div>

CSS:

.container {
  position: relative; 
  width: 400px; /** optional **/
  height: 400px; /** optional **/
  background-color: red; /** optional **/
}

.text {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center; /** Y-axis align **/
  justify-content: center; /** X-axis align **/
}


来源:https://stackoverflow.com/questions/18147642/css-centering-absolute-positioned-text-inside-relative-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!