问题描述
我有一个非常基本的flex设置,无论出于何种原因,有问题的div都不会在其父标记内垂直居中。您可以在下面看到隔离的测试用例。
I have a pretty basic flex setup and, for whatever reason, the div in question won't vertically center inside its parent tag. You can see the isolated test case below.
.likeness-rank-table {
border-radius: 3px;
margin-bottom: 20px;
display: block;
}
.likeness-rank-table .col {
box-sizing: border-box;
text-align: center;
position: relative;
flex: 1;
max-width: 20%;
min-height: 50px;
display: flex;
flex-wrap: wrap;
}
.likeness-rank-table .col .col-inner {
flex: 1;
align-items: center;
justify-content: center;
height: 150px;
}
.likeness-rank-table .likeness-rank-table-body {
display: flex;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border: 1px solid #a2a5a7;
}
.draggable-tags .draggable-tag {
display: inline-block;
float: left;
width: 20%;
margin-bottom: 5px;
}
.draggable-tag {
text-align: center;
padding: 0 15px;
box-sizing: border-box;
}
.draggable-tag .draggable-tag-inner {
position: relative;
padding: 10px 0;
background-color: #63b3ce;
color: #fff;
}
<div class="likeness-rank-table">
<div class="likeness-rank-table-body">
<div class="col">
<div class="col-inner droppable">
<div class="draggable-tag ui-draggable">
<div class="draggable-tag-inner">
This Blue Box Should Be Horizontally and Vertically Centered Inside The Big White Box But It's Not
</div>
</div>
</div>
</div>
</div>
</div>
这是一个Codepen看到它:
Here's a codepen to see it:
推荐答案
某些弹性属性仅适用于弹性商品,而
There are certain flex properties that are applicable only on flex items, while others are only applicable on flex containers.
align-items
和 justify-content
属性仅适用于flex容器。但是,您是在弹性商品上使用它们的。
The align-items
and justify-content
properties apply only to flex containers. Yet, you are using them on a flex item...
.likeness-rank-table .col .col-inner {
flex: 1;
align-items: center;
justify-content: center;
height: 150px;
}
...因此它们被忽略。
... so they are being ignored.
您需要在上述规则中添加 display:flex
。这将使 align-items:center
起作用。
You need to add display: flex
to the rule above. That will get align-items: center
to work.
但是, justify-content :中心
将继续失败,因为父级的最大宽度为:20%
限制了水平移动。
However, justify-content: center
will continue to fail because the parent has a max-width: 20%
limiting horizontal movement.
.likeness-rank-table .col {
box-sizing: border-box;
text-align: center;
position: relative;
flex: 1;
max-width: 20%; /* limits horizontal centering of child element */
min-height: 50px;
display: flex;
flex-wrap: wrap;
}
因此,将水平居中位置应用于父级的另一个水平。
So, apply the horizontal centering to the parent another level up.
.likeness-rank-table .likeness-rank-table-body {
display: flex;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border: 1px solid #a2a5a7;
justify-content: center; /* new */
}
这是一个有用的列表父级和子级细分的弹性属性:
Here's a useful list of flex properties broken down by parent and child: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
这篇关于Flexbox-调整内容:居中和对齐项目:居中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!