Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align absolutely positioned element with flexbox

Tags:

html

css

flexbox

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.

like image 415
panthro Avatar asked Jun 02 '16 14:06

panthro


People also ask

Can you use position absolute with Flexbox?

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.

How do you center an absolute position vertically?

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.

How do I vertically center a div with Flex?

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.


1 Answers

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:

  • Element will not stay centered, especially when re-sizing screen
like image 76
Michael Benjamin Avatar answered Oct 26 '22 23:10

Michael Benjamin