justify-content: center和 align-items:center

当你使用flex布局时 会经常用到这两个属性但是有时会发现为什么失灵了,为什么怎么样都居中不了,明明刚才还管用 ,(前几天博主就遇到了这种情况)…

  • 这个连个属性在网上查到的都是说前者是水平居中后者是垂直居中 但是其实这种是不完全正确的只是其中一种情况,如果是另一种情况的话就会失效。
  • 步入正题那现在应该怎么使用呢?

话不多说上代码:

/*父盒子*/
.testParent{
    width: 700px;
    height: 200px;
    display: flex;
    flex-direction: row; /*默认也是row可以不写*/
    background-color: #428BCA;
    align-items: center;  /*这种情况是垂直居中*/
    justify-content: center;/*这种情况是水平居中*/

}
/*子盒子*/
.test{
    width: 100px;
    height: 50px;
    background-color: aqua;
}


这个时候他就是正常的 justify-content: center是水平居中
align-items:center垂直居中。

  • 但是当我们使用 lex-direction:column;的时候却发现怎么失灵了。
.testParent{
    width: 700px;
    height: 200px;
    display: flex;
    flex-direction: column; /*这里变成了column*/
    background-color: #428BCA;
    align-items: center;  /*这个时候这个变成了水平居中*/

}
/*子盒子*/
.test{
    width: 100px;
    height: 50px;
    background-color: aqua;
}


经过上面的演示总结出来他们的该怎么使用

  • 当你在父盒子中使用 flex-direction: column; 让子元素 竖着排列时 这个时候想水平居中就是用 这个 align-items:center; 。垂直(纵向)居中就是用justify-content: center; 当父盒子 flex-direction: row;(默认的)则反之。
  • 使用这两个属性还有一个前提那就是父盒子的宽度和高度得有,这个时候或许有人会有疑惑,我以前没指定过为什么也能用,原因是子盒子指定了把父盒子的给撑开了,但是如果是垂直方向上可能就会有问题,比如你想让一个盒子在一个页面的正中间,这个时候你就需要把父盒子的高度设为100%才可以。

更多推荐

flex居中(justify-content: center和 align-items:center )遇坑。