如何对齐两个flexbox元素?

时间:2018-11-22 15:18:53

标签: html css layout flexbox

flexbox出现问题。我试图将两个元素对齐;一个到容器的顶部,另一个到中心。大多数flexbox示例使用的是三个元素,而不是两个元素。所以我尝试了自己的解决方案。

#main {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: space-between;
  height: 100px;
  background-color: #dfdfdf;
}

#box1 {
  display: flex;
  justify-content: flex-end;
  background-color: #ff0000;
}

#box2 {
  display: flex;
  background-color: #00ff00;
}

#dummy {
  display: flex;
  opacity: 0;
}
<div id="main">
  <div id="box1">box1</div>
  <div id="box2">box2</div>
  <div id="dummy">dummy</div>
</div>

...而且我也将其应用于水平案例。

#main {
  display: flex;
  flex: 1;
  flex-direction: row;
  justify-content: space-between;
  height: 100px;
  background-color: #dfdfdf;
}

#box1 {
  display: flex;
  justify-content: flex-end;
  background-color: #ff0000;
  width: 200px;
}

#box2 {
  display: flex;
  background-color: #00ff00;
  width: 100px;
}

#dummy {
  display: flex;
  opacity: 0;
  width: 200px;
}
<div id="main">
  <div id="box1">box1</div>
  <div id="box2">box2</div>
  <div id="dummy">dummy</div>
</div>

但是,它需要一个无用的伪元素。我认为这不是一个好主意:(

有没有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:1)

您不必添加此“虚拟” div。根据我的说法,您应该在容器中保持显示弹性,但是将justify-content:中间的空间更改为justify-content:中心。

然后只需在子元素中首先向您添加绝对位置,然后将其显示在容器的顶部。还请记住将相对位置添加到您的容器中。

这是工作代码:

#main {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: center;
  height: 100px;
  background-color: #dfdfdf;
  position: relative;
}

#box1 {
  display: flex;
  justify-content: flex-end;
  background-color: #ff0000;
  position:absolute;
  top:0;
  width:100%;
}

#box2 {
  display: flex;
  background-color: #00ff00;
}

提琴:https://jsfiddle.net/95Lwcbuk/1/

答案 1 :(得分:0)

如果只想使用flex-box,则可以在每个盒子周围包装另一个.container元素,将它们也设置为也使用flex,但是将第一个设置为justify-content: flex-start,将最后一个设置为{ {1}}。

查看示例

justify-content: flex-end
#main {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: center;
  height: 100px;
  background-color: #dfdfdf;
}
.container {
  flex-basis:50%;
  display:flex;
  flex-direction:column;
}
.container:first-child {
  justify-content: flex-start;
}
.container:last-child {
  justify-content: flex-end;
}
#box1 {
  background-color: #ff0000;
}
#box2 {
  background-color: #00ff00;
}