我有一个Div和span。我使用span作为标题元素。所以它应该只出现在:悬停。它使用正常工作:悬停类。
但是如何确保span元素恰好位于父元素的中间,如下图所示。
而不是
请注意,span元素的宽度不固定。
答案 0 :(得分:3)
只需将left: 50%
添加到您的演示(here updated)
.hasToolTip {
width: 30px;
height: 30px;
margin: 100px;
background-color: red;
position: relative;
}
.title {
visibility: hidden;
position: absolute;
top: -30px;
left: 50%;
transform: translateX(-50%);
white-space: nowrap; /* so text don't break line when have space char */
}
.hasToolTip:hover .title {
visibility: visible;
}
<div class="hasToolTip">
<span class="title">16753r2364</span>
</div>
<div class="hasToolTip">
<span class="title">16753r2364and then some</span>
</div>
答案 1 :(得分:2)
您可以在父元素中使用flex
和justify-content: space-around
:
.hasToolTip {
width: 30px;
height: 30px;
margin: 100px;
background-color: red;
position: relative;
display: flex; /* add flex */
justify-content: space-around; /* add this */
}
.title {
visibility: hidden;
position: relative; /* change to relative */
top: -20px; /* decrease top a bit */
left: 0px;
white-space: nowrap; /* for scenarios with very long text with spaces */
}
.hasToolTip:hover .title {
visibility: visible;
}
<div class="hasToolTip">
<span class="title">16753r2364</span>
</div>
<div class="hasToolTip">
<span class="title">16753asdasdasdasasdr2364</span>
</div>
<div class="hasToolTip">
<span class="title">16753asdasdasdasasdr2364 asdasdasdasdasdasdadas</span>
</div>
<强>参考强>
答案 2 :(得分:1)
这是你所追求的,将鼠标悬停在底部div上:
.hasToolTip {
width: 30px;
height: 30px;
margin: 100px;
background-color: red;
position:relative;
}
.title {
visibility: hidden;
top: -30px;
text-align:center;
position: absolute;
transform: translateX(-50%)
}
.hasToolTip:hover .title {
visibility: visible;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="hasToolTip">
<span class="title">16753r2364</span>
</div>
<div>
<div style='text-align:center'>
<div class="hasToolTip">
<span class="title">16753r2364</span>
</div>
</div>
</body>
</html>
&#13;
答案 3 :(得分:0)
您只需应用transform
,例如transform: translateX(-50%)
。在变换中,%是元素本身,而不是您可能期望的父元素。