Center content in a absolute positioned div

余生长醉 提交于 2019-12-12 07:46:34

问题


I have an absolutly positioned element with content inside. It can be a <h1> or a few <p> tag. So I don't know the height of the content.

How can I vertically center the content inside the absolutly positioned div?

HTML :

<div id="absolute">
    <div class="centerd">
    <h1>helo</h1>
    <span>hi again</span>
    </div>
</div>   

CSS :

#absolute {
    position:absolute;
    top:10px;
    left:10px;
    width:50%;
    height:50%;
    background:yellow;
}

.centerd {
    display:table-cell;
    vertical-align:middle;
}

Fiddle


回答1:


if you add display:table to your #absolute div you should get what you want:

http://jsfiddle.net/3KTUM/2/




回答2:


Horizontal and vertical position absolute middle.

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50% , -50%);
  -webkit-transform: translate(-50%, -50%);
}
<div class="obj">
  <div class="center">Test</div>
</div>



回答3:


Change your #absolute div to also use:

display:table;
vertical-align:middle;
text-align:center;

http://jsfiddle.net/3KTUM/4/




回答4:


This can be done with flexbox too:

#absolute {
  align-items: center;
  display: flex;
  justify-content: center;
}



回答5:


Just make the div relative to its absolute parent and use text-align: center, like this:

.centerd {
    position: relative;
    width: 100%;
    text-align: center;
    /*display:table-cell;
    vertical-align:middle;*/
}

See example fiddle




回答6:


use text-align:center or left:50%



来源:https://stackoverflow.com/questions/16239030/center-content-in-a-absolute-positioned-div

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