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.
CSS : centering absolute positioned text inside relative parent
Asked Answered
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.
I'm no css guy, but the explanation was so fine, I really enjoyed the answer and it helped me fix my issue as well. –
Undergarment
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 **/
}
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%;
}
© 2022 - 2024 — McMap. All rights reserved.
position:absolute;
in your .text class CSS ? I just tried removing that line and the text is correctly centered; – Raffarty