Vertical Centering some Text over an Image with Dynamic Height

前端 未结 2 1936
[愿得一人]
[愿得一人] 2020-12-11 21:53

For whatever reason I am really beating myself up with this... No doubt because of the lack of support for a real \"proper\" way of vertically centering anything.

相关标签:
2条回答
  • 2020-12-11 22:17

    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()).

    0 讨论(0)
  • 2020-12-11 22:38

    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.

    0 讨论(0)
提交回复
热议问题