<分区>
<分区>
我对 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>
但是,它需要一个无用的虚拟元素。我认为这不是一个好主意:(
有没有更好的办法解决这个问题?
最佳答案
您不必添加这个“虚拟”div。根据我的说法,您应该在容器中保持 display flex,但将 justify-content: space-between 更改为 justify-content: center。
然后简单的给你先添加绝对位置,子元素显示在容器的顶部。还要记得将相对位置添加到您的容器中。
这里是工作代码:
#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;
}
fiddle :https://jsfiddle.net/95Lwcbuk/1/
关于html - 如何对齐两个 flexbox 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53433962/