在flex儿童中垂直居中内容

时间:2017-02-17 13:32:06

标签: html css flexbox

使用Flexbox我有这个简单的例子..



.container {
   display:flex;
   flex-direction:column;
   align-items:center;
   justify-content:center;
   height:100vh;
}

.box1{height:100%;background:green;}
.box2{height:100%;background:red;}
.box3{height:100%;background:yellow;}

<div class="container">
    <div class="box1">
        <img src="https://dummyimage.com/100x100/000/fff">
    </div>
    <div class="box2">
        This is some dummy text
    </div>
    <div class="box3">
        <img src="https://dummyimage.com/100x100/0020/66t">
    </div>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/y07xr5q3/1/

我希望每个div的内容都是垂直居中的,这是应该使用标准CSS技术完成的,还是有一种灵活的特定方式来实现它?

2 个答案:

答案 0 :(得分:2)

<强>步骤:

  1. 使用display: flex;
  2. 使您的子元素成为容器的Flex容器
  3. 使用align-items: center设置垂直对齐方式。
  4. 必要的CSS:

    div.box {
      align-items: center;
      display: flex;
    }
    

    .container {
      display:flex;
      flex-direction:column;
      align-items:center;
      justify-content:center;
      height:100vh;
    }
    
    .box {
      align-items: center;
      display: flex;
    }
    
    .box1{height:100%;background:green;}
    .box2{height:100%;background:red;}
    .box3{height:100%;background:yellow;}
    <div class="container">
        <div class="box box1">
            <img src="https://dummyimage.com/100x100/000/fff">
        </div>
        <div class="box box2">
            This is some dummy text
        </div>
        <div class="box box3">
            <img src="https://dummyimage.com/100x100/0020/66t">
        </div>
    </div>

答案 1 :(得分:1)

试试这个

&#13;
&#13;
.container {
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  height:100vh;
}
.box1, .box2, .box3 {
	display: flex;
	align-items: center;
}
.box1{height:100%;background:green;}
.box2{height:100%;background:red;}
.box3{height:100%;background:yellow;}
&#13;
<div class="container">
    <div class="box1">
        <img src="https://dummyimage.com/100x100/000/fff">
    </div>
    <div class="box2">
        This is some dummy text
    </div>
    <div class="box3">
        <img src="https://dummyimage.com/100x100/0020/66t">
    </div>
</div>
&#13;
&#13;
&#13;

现场演示https://jsfiddle.net/grinmax_/y07xr5q3/4/