I have a div that is absolutely positioned.
I'm trying to vertically align it with flex:
.container{
position: absolute;
display: flex;
align-items: center;
justify-content: center;
....
HTML:
<div class="container">
<div>
<p>hello</p>
<p>to</p>
<p>you</p>
...
Is this possible? How else can I vertically align .container
? Please note, I do not wish to use the stretching method.
position: absolute;
top: 0;
bottom: 0;
left:0;
right:0;
margin: auto;
Also the container could be of any height.
p.s. no tables please.
If you position a flex item absolutely, it no longer participates in the flex layout. This means any flex properties on the item become moot. You can remove them if you like. The box alignment properties still apply to the flex item even if it is absolutely positioned, which means using align-self will have an effect.
To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
Centering Vertically By default flex items will fill vertical space of their parent element. To vertically center our div we can add a single CSS property. By using align-items: center we can vertically center all flex items to the parent container along the cross axis of the flex container.
To center the .container
element with flex, you need to make the parent a flex container.
The justify-content
and align-items
properties are declared on a flex container, but apply to child elements (flex items).
However, since .container
is absolutely positioned, flex won't work:
An absolutely-positioned child of a flex container does not participate in flex layout.
As an alternative, you can try this:
html { height: 100%; }
body {
height: 100%;
position: relative;
}
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
For an explanation of this centering method see this post:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With