1

I am trying to have an image sitting next to some text. The text needs to sit halfway vertically on the image

[IMG]
[IMG] Here is the text
[IMG]

I am getting the following, because the two cell divs are equal width, instead of matching content width:

[IMG]
[IMG]                                Here is the text
[IMG]

The code is preexisting. There is a table container div:

.vertical-align-container {
    display: table;
    table-layout: auto;
    width: 100%;
}

And two table cell divs:

.vertical-align-child {
    display: table-cell;
    vertical-align: middle;
    padding-left: 15px;
}

So no matter what I do, the table cells are equal width. How can I get the first to match content width, and the second to fill the remainder of the container?

HTML:

<div class="vertical-align-container">
    <div class="vertical-align-child" style="padding-left: 0;">
        <img src="path/img.png">
    </div>
    <div class="vertical-align-child">
        <p><a href="#">Here is the text</a></p>
    </div>
</div>

As you can see, I've tried a couple things, but what I've included here is table-layout, which I though was supposed to do exactly this?

Clayton Engle
  • 582
  • 3
  • 17

2 Answers2

2

I think you could approach this with flexbox.

You can use the align-items property for vertical centering.

.container,
.text {
  display: flex;
}

.text {
  align-items: center;
  padding-left: 1rem;
}

.image img {
  display: block;
  width: 100%;
  height: auto;
}
<div class="container">
  <div class="image">
    <img src="https://unsplash.it/200">
  </div>
</div>
<div class="container">
  <div class="image">
    <img src="https://unsplash.it/200">
  </div>
  <div div class="text">
    <p>
      <a href="#">Here is the text</a>
    </p>
  </div>
</div>
<div class="container">
  <div class="image">
    <img src="https://unsplash.it/200">
  </div>
</div>
sol
  • 22,311
  • 6
  • 42
  • 59
  • I'm going to accept this as the answer, as it's a great modern solution to the problem, however I am working in a legacy system where the display: table-cell needs to stay in place. I added an answer below for anyone looking for a breadcrumb to a legacy answer. – Clayton Engle Jan 19 '18 at 19:49
  • @ClaytonEngle Apologies I didn't know you were stuck with `table` ... best of luck – sol Jan 19 '18 at 19:52
  • 1
    Yeah, my bad for not clarifying that better. Have a good weekend! – Clayton Engle Jan 19 '18 at 19:52
0

Found an ugly workaround for this here: CSS table column autowidth

The issue I was having was that my image is set to 100% width, while using a max-width of the size I wanted it to stop at. Apparently the table isn't willing to read in the max-width as the content size, so it chose 50%.

I hacked in a width for the image and set the table cell to have nowrap, as in the linked question. It's not by any means a good answer, but it'll do for a quick fix.

Clayton Engle
  • 582
  • 3
  • 17