2016-07-28 95 views
2

我有一个Div和跨度里面。我使用span作为标题元素。所以它应该只出现在:hover上。它工作正常使用:悬停类。居中对齐的子绝对元素超过父宽度

但是我怎样才能确保span元素完全出现在父母的中间,就像在下面的图片中一样。

enter image description here

代替

enter image description here

请注意span元素的宽度是不固定的。

fiddle

+0

两种解决方案的工作(以下答案)如果你的浏览器支持高(如在supporing很多老的浏览器),然后使用它不是为我工作的非柔性方式 – Huangism

回答

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>

0

您可以简单地套用一个transformtransform: translateX(-50%)。在转换%是元素本身,而不是你所期望的父。

+1

。你可以更换链接 – Exception

2

您可以在父元素使用flexjustify-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>

参考

flex

justify-content

+0

谢谢。它超级酷。但接受下面,因为我不能使用你的解决方案。 – Exception

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; 
 
}
<!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>

http://jsbin.com/zonopukeku/1/edit?html,css,js,output

相关问题