垂直居中并左对齐一列弹性项目

Vertically center and left-align a column of flex items

要求

  1. flexbox
  2. 垂直居中
  3. 水平向左
  4. 垂直堆叠子元素
  5. 子元素个数可以是一个也可以是多个
  6. 使用旧语法以便Android 4.2 理解

听起来很难描述。演示中的粉红色框是我想要的外观。绿框已经不错了,就是不知道多子元素怎么办

我认为解决方案可能是以下组合,但我做不到。

align-items: center;
flex-direction: column;

body {
  margin: 1em .5em;
}
article {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

section {
  height: 18em;
  background: #ccc;
  margin: 0 .5em;
  position: relative;
  display: flex;
  align-items: center;
}
section:after {
  font-size: smaller;
  color: blue;
  position: absolute;
  bottom: 0;
}
section.big {
  width: 20%;
  height: 5em;
}
section.small {
  width: 10%;
  flex: 1;
}
section div {
  outline: 1px dotted green;
}
section.want {
  background-color: pink;
}
section.want:after {
  content: "1) want to do like this: vertically middle, horizontally left, while section will contain one or several child elements";
}
section.only1 {
  background-color: lightgreen;
}
section.only1:after {
  content: "2) all good except one point:the number of child element must be one.";
}
section.row:after {
  content: "3) by default flex-diraction is row";
}
section.col {
  flex-direction: column;
}
section.col:after {
  content: "4) this can vertically stack multiple stacks, but they no longer horizontally left-align";
}
section.col.justify {
  justify-content: center;
  align-items: flex-start;
  background-color: lightblue;
}
section.col.justify:after {
  content: "6) this is good!  Solved.";
}
section.colmar {
  flex-direction: column;
}
section.colmar:after {
  content: "5) this can vertically stack multiple stacks, and left-align divs, but divs are not vertically center";
}
section.colmar div {
  margin-right: auto;
}
<article>
  <section class="small want">
    line1
    <br/>line2
  </section>
  <section class="small only1">
    <div>only 1 div</div>
  </section>
  <section class="small row">
    <div>div1</div>
    <div>div2</div>
  </section>
  <section class="small col">
    <div>div1</div>
    <div>div2</div>
  </section>
  <section class="small colmar">
    <div>div1</div>
    <div>div2</div>
  </section>
  <section class="small col justify">
    <div>div1</div>
    <div>div2</div>
  </section>
</article>

codepen demo

justify-content 沿主轴对齐弹性项目。

align-items 沿横轴对齐弹性项目,横轴始终垂直于主轴。

根据flex-direction,主轴可能是水平的也可能是垂直的。

由于 flex-direction:column 表示主轴是垂直的,您需要使用 justify-content 而不是 align-items 来使弹性项目居中。

这是一个例子:

#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 200px;
  background-color: lightpink;
}
<div id="container">
  <div class="box">div 1</div>
  <div class="box">div 2</div>
  <div class="box">div 3</div>
  <div class="box">div 4</div>
  <div class="box">div 5</div>
</div>

在此处了解有关沿 主轴 弯曲对齐的更多信息:

在此处了解有关沿 横轴 弯曲对齐的更多信息:

我想如果你将列 div 垂直放置在包装器 div 的中心(让我们称它为你的行 div):

align-self: center;

并将div列的内容放在中间:

text-align: center;

它会按照你想要的方式工作。

设置高度解决了我的问题。