css 居中对齐div [重复]

lyfkaqu1  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(54)

此问题在此处已有答案

How can I vertically center a div element for all browsers using CSS?(48个回答)
9天前关闭
我想在中心水平和垂直对齐id为content的元素。我已经尝试使用justify-content: center;align-items: center;,但似乎都不起作用。我想保持绝对位置,因为它将作为一个弹出窗口显示在中心。

#field {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
}
#content {
    width: 100px;
    height: 50px;
    margin: auto;
        background-color: black;
}

个字符

np8igboo

np8igboo1#

justify-contentalign-items用于flexbox。您必须使用display: flexbox;参见下面的示例:

#field {
    width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;

}
#content {
    width: 100px;
    height: 50px;
    margin: auto;
        background-color: black;
}

个字符

**使用position: absolute;更新代码:**您可以保留position: absolute;,但仍然可以对容器进行flexbox。请参见下面的示例:

#field {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}
#content {
    width: 100px;
    height: 50px;
    background-color: black;
}
<div id="field">
    <div id="content">
    </div>
</div>

的字符串

相关问题