在下面的代码中,.hover-tooltip
是宽度设置为max-content
的div。我想将此div放在父div .hover-wrap
的中心,而不考虑它的宽度,因为.hover-tooltip
内的内容是动态的。我试过left: 50%;
和margin-left: calc(50% - 10px)
,但没有运气。
$(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>
&#13;
由于
答案 0 :(得分:4)
试试这个
.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%);
}