Kevin LeStarge Kevin LeStarge - 2 months ago 9
CSS Question

Vertically center element after title with dynamically loaded text all within a static container

This is driving me crazy and I don't think it is even possible at this point, but I would like to consult the Internet Gods before I give up.

Visual representation of what I want:

Visual representation of what I want

I want the text to align at the top-left of the container, and the image to align itself in the center of the space that is leftover after (if) the text wraps.

Please see demo

I'm using

flexbox
and
margin: 0 auto
to get the centering I want, and
position: absolute
on the
h2
element works fine if the image is long, but looks terrible with tall image.

Is there some flexbox magic I can use to take into account the height of the dynamically loaded h2 element and make the image centered within the rest of the free space?

Constraints:


  • The parent container must be 200px by 200px.

  • Image can not be distorted (stretched).


Answer

I was able to find my own solution by combining @Claudio's table idea and some position absolute magic.

Here is the solution demo with both tall and wide images: DEMO

HTML:

<div class="main-box">
  <table>
    <tr>
        <td class="box-title">
            <h2>
                My title here. :) add some more text
            </h2>
        </td>
    </tr>
    <tr>
        <td class="box-img">
            <img src="//i.imgur.com/NOzWHFF.png" alt="Google">
        </td>
    </tr>
  </table>
</div>
<div class="main-box">
  <table>
    <tr>
        <td class="box-title">
            <h2>
                My title here. :) add some more text
            </h2>
        </td>
    </tr>
    <tr>
        <td class="box-img">
            <img src="https://upload.wikimedia.org/wikipedia/commons/e/e0/Long_March_2D_launching_VRSS-1.jpg" alt="Google">
        </td>
    </tr>
  </table>
</div>

CSS:

*{
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
.main-box{
    width: 200px;
    height: 200px;
    border: 2px solid #000;
    background-color: #FFF;
    position: relative;
}
.main-box table{
    width: 100%;
    height: 100%;
    border-spacing:0;
}
.main-box .box-title{
    background-color: rgba(0, 0, 0, 0.1);
    height: 1px;
}
.main-box .box-title h2{
    margin: 0;
    padding: 5px;
    font-family: Helvetica, Arial, sans-serif;
}
.main-box .box-img{
    text-align: center;
    vertical-align: middle;
    padding: 5px;
    position: relative;
}
.main-box .box-img img{
    max-width: 100%;
    max-height: 100%;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}