html - 带过渡的垂直居中文本

标签 html css css-transitions flexbox

我正在使用 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

DEMO


如果从 .overbox 中删除 padding: 0.9375rem,两个框对齐并且文本完全水平居中。

DEMO


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;
}

DEMO


来自规范:

8.3. Cross-axis Alignment: the align-items and align-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 property

The align-content property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to how justify-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/

相关文章:

html - 部分宽度边框

javascript - 渐变不适用于 iOS 设备

javascript - 根据类名修改 <span/> 文本 JAVASCRIPT - 无 jQUERY

jquery - 在 jQuery 中更改类并在单击时获取值

javascript - 如果不存在合适的 ARIA 属性,我是否应该使用自定义 ARIA 属性?

firefox - 如何为所有属性指定 CSS3 过渡,但有一个异常(exception)/覆盖?

javascript - 单击时使图像填满屏幕

javascript - 世界地图粒子效果javascript

javascript - 将 div 或 svg 转换为 datauri

html - 如何装箱并单独为该文本着色?