Felix Maxime Felix Maxime - 6 months ago 34
HTML Question

Center text over images with flexbox

I want to add centered text on images on hover.

This is what I've got.

enter image description here

I've tried moving the text up forcefully with

margin-top
, but the results on a page resize are inconsistent.

Any ideas how to center this text?



.featuredText {
position: absolute;
-webkit-box-flex: auto;
-ms-flex: auto;
flex: auto;
text-align: center;
}

<div>
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-1.jpg" alt>
<div class="centeredText">text</div>
</div>




Answer

#container {
    display: inline-flex;
    position: relative;              /* establish nearest positioned ancestor for abspos */
    cursor: pointer;
}

.centeredText {
    display: none;
}

#container:hover > .centeredText {
    display: inline-block;
    font-size: 4em;
    color: white;
    position: absolute;               /* remove from document flow */
    left: 50%;                        /* center horizontally */
    top: 50%;                         /* center vertically */
    transform: translate(-50%,-50%)   /* tweak for precise centering; details:
                                       http://stackoverflow.com/q/36817249 */
}
<div id="container">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-1.jpg" alt>
    <div class="centeredText">text</div>
</div>

https://jsfiddle.net/oqya3a3y/

Comments