使用flexbox垂直对齐绝对定位的元素

pan*_*hro 4 html css html5 css3 flexbox

我有一个绝对定位的div.

我正试图将它与flex垂直对齐:

.container{
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    ....
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="container">
    <div>
        <p>hello</p>
        <p>to</p>
        <p>you</p>
        ...
Run Code Online (Sandbox Code Playgroud)

这可能吗?我怎么能垂直对齐.container?请注意,我不想使用拉伸方法.

 position: absolute;
 top: 0;
 bottom: 0;
 left:0;
 right:0;
 margin: auto;
Run Code Online (Sandbox Code Playgroud)

容器也可以是任何高度.

ps没有桌子.

Mic*_*l_B 10

.container使用flex 中心元素,您需要使元素成为flex容器.

justify-contentalign-items属性宣布Flex容器,而是可以应用到子元素(弯曲项).

但是,由于.container绝对定位,flex不起作用:

Flex容器的绝对定位子项不参与flex布局.

作为替代方案,您可以尝试这样做:

html { height: 100%; }

body {
   height: 100%;
   position: relative;
}

.container {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%,-50%);
}
Run Code Online (Sandbox Code Playgroud)

有关此居中方法的说明,请参阅此帖子: