我在另一个 div 容器中有 2 个 div。我正在使用 flexbox 将它们在容器内垂直居中,但我希望它们在水平方向上彼此相邻,而不是一个在另一个之上。我尝试了几种不同的方法,包括将容器的 display
属性从 flex
更改为 inline-flex
以及添加 display: inline-block
到子 div。这是我正在使用的图片。如您所见,2 个 div(图片和第 1 组标签)位于父 div 的中心,但我希望第 1 组位于图片旁边而不是图片下方。
下面的代码和链接到 JSfiddle :
HTML
<div class="user-group">
<div>
Picture 1
</div>
<div class="user-group-name"><h4>Group 1</h4></div>
</div>
JS
.user-group{
font-family: 'Purista';
border: solid 1px;
display: inline-flex;
float: left;
justify-content:center;
align-content:center;
flex-direction:column; /* column | row */
width: 50%;
height: 200px;
}
.user-group > div{
display: inline-flex;
}
最佳答案
这取决于您是否打算在元素中包含多个图片 + 文本对。如果不这样做,只需使用 align-items: center
应该解决你的问题。您的代码存在一些问题:
-
align-content
不是 flex 属性 - 避免使用
display: inline-flex
, 你的情况不需要它 - float 和 flex 是相互冲突的布局方法。选择一个——在这种情况下,我们选择 flex 。
- 使用默认的 flex 方向,即
row
(如果未声明,它默认为row
,因此我们可以删除该属性)
.user-group {
font-family: 'Purista';
border: 1px solid;
display: flex;
justify-content: center;
align-items: center;
width: 50%;
height: 200px;
}
h4 {
margin: 0;
}
<div class="user-group">
<div>
<img src="https://placehold.it/32x32" alt="" title="" />
</div>
<div class="user-group-name">
<h4>Group 1</h4></div>
</div>
另一方面,如果您有多个图片 + 文本对,您将不得不求助于嵌套。每对都必须用额外的 <div>
包裹:
.user-group {
font-family: 'Purista';
border: 1px solid;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 50%;
height: 200px;
}
.user-group > div {
display: flex;
margin-bottom: 10px;
}
h4 {
margin: 0;
}
<div class="user-group">
<div>
<img src="https://placehold.it/32x32" alt="" title="" />
<div class="user-group-name"><h4>Group 1</h4></div>
</div>
<div>
<img src="https://placehold.it/32x32" alt="" title="" />
<div class="user-group-name"><h4>Group 2</h4></div>
</div>
<div>
<img src="https://placehold.it/32x32" alt="" title="" />
<div class="user-group-name"><h4>Group 3</h4></div>
</div>
</div>
关于css - 如何使用 flex-box 内联显示两个 div,同时将它们垂直居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40368209/