Vertical Centering some Text over an Image with Dynamic Height

时光总嘲笑我的痴心妄想 提交于 2019-11-28 14:17:45
Hashem Qolami

First, I wasn't sure about what you mean exactly. But as you mentioned:

The issue is centering the text Gallery 1 vertically over the top of the image. Centering it horizontally is easy with a simple text-align but centering it vertically is what is eluding me.

Here is my attempt to align the text vertically over the image. Actually the concept comes from this approach of a similar topic on SO:

.container { position: relative; }

.container img {
    vertical-align: bottom; /* Remove the gap at the bottom of inline image */
    max-width: 100%;
}

.caption {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    font: 0/0 a; /* Remove the gap between inline(-block) elements */
}

.caption:before {
    content: ' ';
    display: inline-block;
    height: 100%;
    vertical-align: middle;    
}

.caption a {
    font: 16px/1 Arial, sans-serif; /* Reset the font property */
    display: inline-block;
    vertical-align: middle;
    text-align:center;
    background: rgba(255, 255, 255, 0.75);
    width: 100%;
    padding: 1% 0; /* Added a relative padding for the demo */
}

WORKING DEMO.

This relies on CSS2.1 and it will definitely work on IE8+ (excluding rgba()).

If I understand your issue correctly, this may work for you:

Working Demo

If you need the image to scale when hovered over, then simply adding a :hover on the container and changing it's width should work.

CSS:

.container {
    // existing styles
    -webkit-transition: all .2s; // needs prefixes for other browsers.
}

.container:hover {
    width: 500px;
}

The only issue is that transition has no support for IE9 or earlier. So you'd need to go a JS route if that is an issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!