垂直居中并左对齐一个 flex 项的列

8 浏览
0 Comments

垂直居中并左对齐一个 flex 项的列

要求

  1. 使用flexbox布局
  2. 垂直居中
  3. 水平左对齐
  4. 垂直堆叠子元素
  5. 子元素数量可以是一个或多个
  6. 使用旧语法以便安卓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) 想要实现这样的效果:垂直居中,水平左对齐,同时section中可以包含一个或多个子元素";
}
section.only1 {
  background-color: lightgreen;
}
section.only1:after {
  content: "2) 所有都好,除了一个问题:子元素的数量必须为一个。";
}
section.row:after {
  content: "3) 默认情况下flex-direction为row";
}
section.col {
  flex-direction: column;
}
section.col:after {
  content: "4) 这可以垂直堆叠多个堆栈,但它们不再水平左对齐";
}
section.col.justify {
  justify-content: center;
  align-items: flex-start;
  background-color: lightblue;
}
section.col.justify:after {
  content: "6) 这很好!问题解决了。";
}
section.colmar {
  flex-direction: column;
}
section.colmar:after {
  content: "5) 这可以垂直堆叠多个堆栈,并左对齐divs,但divs不是垂直居中";
}
section.colmar div {
  margin-right: auto;
}

line1 line2
only 1 div
div1 div2
div1 div2
div1 div2
div1 div2

codepen演示

0
0 Comments

问题的原因是在使用flex布局中,想要实现将一列flex项垂直居中并左对齐。然而,在flex布局中,使用align-items属性是将flex项沿交叉轴对齐,而不是垂直居中。而根据flex-direction的不同取值,主轴可以是水平的或垂直的。当flex-direction:column时,主轴是垂直的,因此需要使用justify-content而不是align-items来实现flex项的垂直居中。

解决方法是在包含flex项的容器上使用以下CSS样式:

#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 200px;
  background-color: lightpink;
}

其中,display: flex;表示将容器设置为flex布局,flex-direction: column;表示主轴方向为垂直,justify-content: center;表示在主轴上将flex项垂直居中,height: 200px;设置容器的高度为200像素,background-color: lightpink;设置容器的背景色为浅粉红色。

通过设置容器的高度,可以让浏览器知道在哪个位置放置flex项,从而实现垂直居中和左对齐的效果。

在文章中还提供了有关flex布局在主轴和交叉轴上对齐的更多信息的链接,供读者进一步学习。

解决问题的关键是使用justify-content属性来实现flex项的垂直居中,并通过设置容器的高度来确定放置flex项的位置。

0
0 Comments

问题的原因是flex项目默认是垂直居中和左对齐的,而需要将其垂直居中和左对齐。

解决方法是设置flex项目的高度。

0
0 Comments

问题出现的原因是想要在一个flex容器中垂直居中和左对齐一列flex项目。为了解决这个问题,可以使用以下方法:

首先,在包裹容器(div)中使用align-self: center;将列(div)垂直居中。

然后,将列(div)中的内容使用text-align: center;实现内容的水平居中。

这样就可以实现所需的效果了。

0