Search code examples
htmlcssposition

Dynamic width DIV at center of parent


In the code below, .hover-tooltip is a div with width set to max-content. I want to position this div at the center of parent div .hover-wrap irrespective of its width because content inside .hover-tooltip is dynamic. I tried with left: 50%; and margin-left: calc(50% - 10px) but with no luck.

$(document).on('mouseenter', '.hover-wrap', function(){
  $(this).find('.hover-tooltip').show();
});

$(document).on('mouseleave', '.hover-wrap', function(){
  $(this).find('.hover-tooltip').hide();
});
table{
margin-top: 100px;
}

.hover-wrap{
position: relative;
padding: 5px;
background: #eee;
}

.hover-div{
width: 65px;
height: 65px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}

.hover-tooltip{
position: absolute;
bottom: calc(100% + 10px);
background: #555;
color: #fff;
font-size: 13px;
padding: 10px;
border-radius: 4px;
width: max-content;
display: none;
margin: auto;
}

.hover-tooltip:before{
content: '';
position: absolute;
left: 50%;
top: 100%;
margin-left: -5px;
border-top: 10px solid #555;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="hover-wrap">
      <div class="hover-div">1</div>
      <div class="hover-tooltip">This is tooltip</div>
    </td>
    <td class="hover-wrap">
      <div class="hover-div">1</div>
      <div class="hover-tooltip">Small</div>
    </td>
    <td class="hover-wrap">
      <div class="hover-div">1</div>
      <div class="hover-tooltip">This is a long tooltip</div>
    </td>
    <td class="hover-wrap">
      <div class="hover-div">1</div>
      <div class="hover-tooltip">This is a very very very long tooltip</div>
    </td>
  </tr>
</table>

Thanks


Solution

  • try this

    .hover-tooltip {
        position: absolute;
        bottom: calc(100% + 0px);
        background: #555;
        color: #fff;
        font-size: 13px;
        padding: 10px;
        border-radius: 4px;
        width: max-content;
        display: none;
        margin: auto;
        left: 50%;
        -moz-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
    }