Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text over images with flexbox [duplicate]

Tags:

html

css

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>
like image 585
Felix Maxime Avatar asked May 18 '16 22:05

Felix Maxime


1 Answers

#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">
  <div class="centeredText">text</div>
</div>

jsFiddle

like image 102
Michael Benjamin Avatar answered Sep 19 '22 10:09

Michael Benjamin