我有一个Div和跨度里面。我使用span作为标题元素。所以它应该只出现在:hover上。它工作正常使用:悬停类。居中对齐的子绝对元素超过父宽度
但是我怎样才能确保span元素完全出现在父母的中间,就像在下面的图片中一样。
代替
请注意span元素的宽度是不固定的。
我有一个Div和跨度里面。我使用span作为标题元素。所以它应该只出现在:hover上。它工作正常使用:悬停类。居中对齐的子绝对元素超过父宽度
但是我怎样才能确保span元素完全出现在父母的中间,就像在下面的图片中一样。
代替
请注意span元素的宽度是不固定的。
只需添加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>
您可以在父元素使用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>
参考
谢谢。它超级酷。但接受下面,因为我不能使用你的解决方案。 – Exception
这里是你的你是什么后,将鼠标悬停在底部的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;
}
<!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>
两种解决方案的工作(以下答案)如果你的浏览器支持高(如在supporing很多老的浏览器),然后使用它不是为我工作的非柔性方式 – Huangism