CSS 在绝对定位的 div 中居中内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16239030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:38:11  来源:igfitidea点击:

Center content in a absolute positioned div

csscss-positioncentering

提问by user2324261

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.

我有一个绝对定位的元素,里面有内容。它可以是一个<h1>或几个<p>标签。所以我不知道内容的高度。

How can I vertically center the contentinside the absolutly positioned div?

如何将绝对定位内的内容垂直居中div

HTML :

HTML :

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

CSS :

CSS :

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

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

Fiddle

小提琴

采纳答案by Pete

if you add display:tableto your #absolutediv you should get what you want:

如果你添加display:table到你的#absolutediv 你应该得到你想要的:

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

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

回答by Celil ?ahin

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>

回答by James Donnelly

Change your #absolutediv to also use:

将您的#absolutediv更改为也使用:

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

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

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

回答by Andrés

This can be done with flexbox too:

这也可以用 flexbox 来完成:

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

回答by Nelson

Just make the div relativeto its absoluteparent and use text-align: center, like this:

只需将 divrelative设置为absolute其父级并使用text-align: center,如下所示:

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

See example fiddle

参见示例小提琴

回答by santhosh

use text-align:center or left:50%

使用 text-align:center 或 left:50%