Search code examples
htmlcssvertical-alignmentvertical-text

Vertically centered text in a dynamic height wrapper


I'd normally just use line-height for vertical centering, but on this occasion the layout I'm working to is a little trickier.

I've put together this jsfiddle to show where I'm at so far. All the CSS hacks suggest using table-cell trickery for this but I can only get it to work if the wrapper has an absolute height, so for me this text isn't vertically centered:

<div class="wrap">
    <a href="#">
        <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
        <span class="text"><span>Text that might span multiple lines</span></span>
    </a>
</div>

https://jsfiddle.net/fdtbvmcw/

What I basically need is for the text, regardless of how many lines it spans, to sit in the middle of the image. The image can't be a background-image and I can't attach fixed widths or heights to the wrapper.

The wrapper is simulating a responsive column within a bigger page template and I need the image to retain full width of that column you see. Other HTML can be added within the column if need be.

Thoughts?


Solution

  • Flexbox can do that...

    .wrap {
      height: auto;
      position: relative;
      width: 50%;
    }
    
    .wrap a img {
      height: auto;
      width: 100%;
    }
    
    .wrap a span.text {
      height: 100%;
      left: 0;
      position: absolute;
      text-align: center;
      top: 0;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .wrap a span.text span {
      color: #fff;
      font-size: 20px;
      font-weight: bold;
      line-height: 1.25
    }
    <div class="wrap">
      <a href="#">
        <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
        <span class="text"><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id praesentium nihil iure amet dolore nulla totam modi </span></span>
      </a>
    </div>