Html CSS:在相对父级内居中绝对定位文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18147642/
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
CSS : centering absolute positioned text inside relative parent
提问by vlad
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.
如何将绝对定位文本居中放置在流体相对父级中?我试图text-align:center
在父元素上使用,但它总是以孩子的左角为中心,而不是元素本身。
回答by amaurymartiny
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.
事情是position:absolute;
修改元素的宽度以适应其内容,并将text-align: center;
文本在元素块的宽度内居中。所以如果你添加了一个position: absolute;
不要忘记增加元素的宽度,否则该text-align: center;
属性将毫无用处。
The best way to solve this is to add a width: 100%;
and a left: 0px;
in the .text section.
解决此问题的最佳方法是在 .text 部分添加 awidth: 100%;
和 a left: 0px;
。
回答by stray
You can now achieve what you want more elegantly with flex. See for example:
您现在可以使用 flex 更优雅地实现您想要的。见例如:
HTML:
HTML:
<div class="container">
<div class="text">Your text</div>
</div>
CSS:
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 **/
}
回答by Gary Kenyon
Update: What I put before was bad/wrong
更新:我之前放的东西是坏的/错误的
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%;
}