如何将工具提示置于比工具提示更窄的元素下方?

时间:2014-11-03 00:40:40

标签: css

我有这个代码将工具提示集中在一个元素下面。它适用于大于或等于工具提示宽度的元素:

HTML:

<div class="my_class">Some Stuff<div class="tooltip_botom">My Very Long Tooltip Contents</div></div>

CSS:

.my_class {
    position: relative;
    width: 100%;
    height: 100%;
}

.tooltip_bottom {
  position: absolute
  bottom: -25px
  left: 0
  right: 0
  display: inline
  text-align: center
}

但是如果内容比工具提示宽度窄,我该怎么办?我在上面列出的CSS在这种情况下不起作用。我该如何解决?

1 个答案:

答案 0 :(得分:2)

查看此新JSFiddle是否适用于您的情况。要使工具提示居中,它使用左50%,transform:translateX(-50%),使用文本对齐中心。

它使用white-space:nowrap来防止文本换行,但是如果文本需要换行,则可以删除它,而是可以使用min和max width的组合来控制或调整工具提示框大小。

CSS

.my_class {
    position:relative;
    display:inline-block;
    white-space:nowrap;
    background-color:#ffffcc;
    padding:3px 9px;
    border:solid 1px #555555;
}
.tooltip_bottom {
    position:absolute;
    display:none;
    text-align:center;
    top:25px;
    left:50%;
    transform:translateX(-50%);
}
.my_class:hover .tooltip_bottom {
    display:block;
    /* To wrap the tooltip text, use min-width/max-width to control tooltip length. Use white-space:normal to overwrite the white-space:nowrap from the wrapper.  
    min-width:145px; 
    white-space: normal; */
    background-color:#ccccff;
    padding:8px;
}

HTML

<div class="my_class">Tooltip Trigger Long
<div class="tooltip_bottom">My Very Long Tooltip Contents</div>
</div>

some text

<div class="my_class">Tooltip Trigger Short
<div class="tooltip_bottom">Short</div>
</div>