【问题标题】:Vertically center a caption on hover悬停时垂直居中标题
【发布时间】:2016-01-21 23:25:41
【问题描述】:

是否可以使用以下代码在悬停时将标题垂直居中?我知道我可以在 figcaption 标记周围添加一个 div 来进行叠加,但我想知道是否可以在不添加更多 HTML 代码的情况下做同样的事情。

HTML:

<figure class="caption">
    <img src="image.jpg" alt="" />
    <figcaption class="caption-text">Some text</figcaption>
</figure>

CSS:

.caption {
    position: relative;
}

.caption img {
    display: block;
    margin: 0;
}

.caption-text {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    color: #fff;
    text-align: center;
}

.caption:hover .caption-text {
    display: block;
    background: rgba(30, 30, 30, 0.7);
}

提前致谢

【问题讨论】:

    标签: html css center vertical-alignment caption


    【解决方案1】:

    你可以在.caption-text上使用Flexbox

    .caption {
        position: relative;
        display: inline-block;
    }
    
    .caption img {
        display: block;
        margin: 0;
    }
    
    .caption-text {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: all 0.3s ease-in;
    }
    
    .caption:hover .caption-text {
        background: rgba(30, 30, 30, 0.7);
        opacity: 1;
    }
    <figure class="caption">
       <img src="http://placehold.it/350x150">
       <figcaption class="caption-text">Some text</figcaption>
    </figure>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 2020-09-03
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多