11

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
  • 307,417
  • 93
  • 525
  • 644
panthro
  • 21,049
  • 61
  • 166
  • 295
  • 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

2 Answers2

23

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
  • 307,417
  • 93
  • 525
  • 644
-2

Your code works fine, and the position: absolute is not necessary for the vertical alignment. See the Code Snippet below. Note that the height is just there to show the vertical alignment; it's not necessary for this to work.

.container{
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid red;
    height: 200px;
  }
<div class="container">
  <div>
    <p>one</p>
    <p>two</p>
    <p>three</p>
  </div>
</div>
JakeParis
  • 10,743
  • 3
  • 37
  • 64
  • 4
    "position: absolute is not necessary for the vertical alignment." it's not, but it is for my layout. – panthro Jun 02 '16 at 14:33