我正在使用 flex 和 transition 来尝试实现一些目标。
以前从未使用过 flex,但认为它可能与我想要实现的目标配合得很好。
请参阅fiddle
我想要实现的是,当您将鼠标悬停在框上时,底部栏会覆盖框(这有效)并且标题和文本会过渡到框的中心。这是一半的工作。
它们水平居中,但不是我想要的垂直居中。文本应该在中心靠得更近。
这是可能的还是我做错了什么?
html
<a href="#" class="box-link row">
<div class="overbox row">
<h4>This is a title</h4>
<p>Lorem ipsum dolor sit amet, usu debet tation cu. Eam assum habemus dignissim ne</p>
</div>
</a>
CSS
.box-link {
display: flex;
flex: 1 1 0px;
flex-flow: row wrap;
width: 19.8125rem;
height: 19.8125rem;
position: relative;
overflow: hidden;
background:red;
text-align: center;
border:1px solid red;
}
.box-link .overbox {
align-items: center;
justify-content: center;
transition: 0.5s ease-in-out;
background-color: rgba(255, 255, 255, 0.6);
min-height: 15%;
width: 100%;
padding: 0.9375rem;
position: absolute;
top: 85%;
left: 0;
display: flex;
flex-flow: row wrap;
}
.box-link:hover .overbox {
min-height: 100%;
position: absolute;
top: 0;
left: 0;
}
h4 {
margin:0;
}
最佳答案
悬停时,由于填充声明,文本相对于容器稍微右对齐。
为了说明,从容器元素 (.box-link
) 中删除 overflow: hidden
。
如果从 .overbox
中删除 padding: 0.9375rem
,两个框对齐并且文本完全水平居中。
flex 元素没有更紧密地垂直居中的原因是因为在具有 flex-direction: row
的多行 flex 容器上, flex 对齐由 align-content< 控制
属性,而不是 align-items
。这就是你所拥有的:
.box-link .overbox {
align-items: center;
justify-content: center;
...
...
...
display: flex;
flex-flow: row wrap;
}
横轴有多条线时使用的属性是align-content
.
将此添加到您的 CSS:
.box-link .overbox {
align-items: center;
justify-content: center;
align-content: center; /* NEW */
...
...
...
display: flex;
flex-flow: row wrap;
}
来自规范:
8.3. Cross-axis Alignment: the
align-items
andalign-self
properties
align-items
sets the default alignment for all of the flex container’s items, including anonymous flex items.align-self
allows this default alignment to be overridden for individual flex items.8.4. Packing Flex Lines: the
align-content
propertyThe
align-content
property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to howjustify-content
aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container.
关于html - 带过渡的垂直居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923951/