12

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.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
panthro
  • 22,779
  • 66
  • 183
  • 324
  • If you want to vertically align the div that has the class `.container` then you should display as flex to its first direct parent and use `align-items: center` (If you want to also use the flex option). – Francisco Romero Jun 02 '16 at 14:21
  • Or if you have something absolute positioned to some container that is display as relative you can set `top`, `bottom`, `left` and `right` to 0 and then use `margin: auto 0`;. Or are you trying to vertical align the content instead of the div that is absolute positioned (`.container`). It is not very clear on the question. – Francisco Romero Jun 02 '16 at 14:23
  • Error404 - your first method does not work, your second method is not what im asking for. – panthro Jun 02 '16 at 14:27
  • Try with `align-content` instead in the first method. – Francisco Romero Jun 02 '16 at 14:29

1 Answers1

25

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:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701