brabertaser19 brabertaser19 - 5 months ago 8
CSS Question

Center absolute block in td vertically

I have such code:



td {
border: 1px solid #cecece;
position: relative;
padding: 80px 20px;
}
.hint {
background: yellow;
position: absolute;
top: 0;
bottom: 0;
left: 100px;
}

<table style="width:800px">
<tr>
<td width="50%">
<span>text</span>
<div class="hint">
<span class="recomendation">Some text with recomendation</span>
</div>
</td>
<td>
<span>text</span>
<div class="hint">
<span class="recomendation">Some text with recomendationSome text with recomendationSome text with recomendation</span>
</div>
</td>
</tr>
</table>





https://plnkr.co/edit/JVkXP3vNtIj4gzwwjm4B?p=preview

But i have one issue, which i can't resolve:

Is it possible to center yellow block vertically? (it should be positioned absolutely, it height can be only as text height is. Without line-height, height is dynamic!). Now it's attached to the top, and i can't attach it to the center somehow. Is it possible without using JS?

Answer

Try using flexbox. All modern browsers support it, with prefixes it also works in IE10.

.hint {
  ...
  display: flex;
  align-items: center;
}

td {
  border: 1px solid #cecece;
  position: relative;
  padding: 80px 20px;
}
.hint {
  background: yellow;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 100px;
  display: flex;
  align-items: center;
}
<table style="width:800px">
  <tr>
    <td width="50%">
      <span>text</span>
      <div class="hint">
        <span class="recomendation">Some text with recomendation</span>
      </div>
    </td>
    <td>
      <span>text</span>
      <div class="hint">
        <span class="recomendation">Some text with recomendationSome text with recomendationSome text with recomendation</span>
      </div>
    </td>
  </tr>
</table>