中心使用flexbox在水平和垂直方向上划分

时间:2015-07-29 10:03:56

标签: html css flexbox

我正在尝试使用flexbox纵向和横向居中一些div,但它没有按预期工作。
这是一张图片,展示了我的目标和期望。

enter image description here

以下是代码:

<html lang="en">

<body>

<style type="text/css">

    body{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
</style>

    <div>111111</div>
    <div>222222</div>
    <div>333333</div>

</body>

</html>

修改

当然,我知道将div放在容器中会更好,这就是我先尝试过的,但在这种情况下,我最终会得到这样的结果:

enter image description here

正如您所看到的,div s按预期集中在容器中,但容器本身不是。

3 个答案:

答案 0 :(得分:6)

您的代码很好,您只应向min-height: 100vh添加body,以便div可以在视口高度居中(正文并不总是覆盖视口高度,只需要包含其子女的最小空间)

示例:http://codepen.io/anon/pen/xGQpKO

答案 1 :(得分:4)

添加此

html, body {
    height: 100%;
}

小提琴:https://jsfiddle.net/1Luo758m/

答案 2 :(得分:1)

您需要对齐内容:中心才能运行

align-content : center

见:

http://css-tricks.com/almanac/properties/a/align-content/

我建议你在div中嵌套对象。改变身体行为是危险的。

相关问题