2014-11-03 43 views
1

我有这段代码将一个工具提示置于一个元素下面。它工作正常的大于或等于提示的宽度的元素:如何将工具提示置于比工具提示更窄的元素下方?

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在这种情况下不起作用。我该如何解决它?

+0

我要的是工具提示到div下方居中。 – 2014-11-03 13:48:33

回答

2

看看这个新的JSFiddle适合您的情况。要使工具提示居中,它将使用左侧50%,transform:translateX(-50%)和文本对齐中心。

它使用white-space:nowrap来保持文本不被缠绕,但是如果文本需要缠绕,可以将其删除,相反,可以使用最小和最大宽度的组合来控制或调整工具提示框大小。

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> 
+0

就是这样!非常感谢!我从来没有见过''transform:translateX''的东西。 – 2014-11-05 03:34:50

+0

不客气:)这个想法来自这个有用的页面 - http://css-tricks.com/centering-css-complete-guide/ – Talkingrock 2014-11-05 04:02:24