居中对齐父级宽度以上的子绝对元素

时间:2016-07-28 19:48:17

标签: css css3

我有一个Div和span。我使用span作为标题元素。所以它应该只出现在:悬停。它使用正常工作:悬停类。

但是如何确保span元素恰好位于父元素的中间,如下图所示。

enter image description here

而不是

enter image description here

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

fiddle

4 个答案:

答案 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)

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

答案 2 :(得分:1)

这是你所追求的,将鼠标悬停在底部div上:

&#13;
&#13;
.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;
&#13;
&#13;

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

答案 3 :(得分:0)

您只需应用transform,例如transform: translateX(-50%)。在变换中,%是元素本身,而不是您可能期望的父元素。