-2

I am trying to create tooltips using css. The idea is to make the tooltip vertically and horizontally centered to its parent element but keep it hidden before moving and displaying it on hover. Anyway, the following is my code:

.tooltip-top {
    position: relative;
}
.tooltip-top::before {
    content: attr(title);
    padding: 1rem 1.5rem;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    position: absolute;
    width: 60px;
}
<a href="#" class="tooltip-top" title="content">Tooltip</a>

As you can see, the tooltip is not centered according to its parent element. I added the styles left: 50%, and top: 50% to it, but it still was not perfectly centered. How can I do this?

darkhorse
  • 5,888
  • 11
  • 39
  • 105
  • 1
    use flex, in the parent container add class with attributes: display:flex;justify-content: center; align-items: center; – juancarlos Sep 27 '19 at 17:31

3 Answers3

1

I added the styles left: 50%, and top: 50% to it, but it still was not perfectly centered

In addition to these properties, add property transform: translate(-50%, -50%);

Result

.tooltip-top {
  position: relative;
}

.tooltip-top::before {
  content: attr(title);
  padding: 1rem 1.5rem;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
  position: absolute;
  width: 60px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<a href="#" class="tooltip-top" title="content">Tooltip</a>
hisbvdis
  • 1,321
  • 1
  • 7
  • 9
-1

Here you go:

.tooltip-top {
    position: relative;
}
.tooltip-top::before {
    content: attr(title);
    padding: 1rem 1.5rem;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    position: absolute;

    width: 60px;
}
<a href="#" class="tooltip-top" title="content">Tooltip</a>
Loki
  • 725
  • 6
  • 29
-2

That's what you wanted?

.tooltip-top {
    position: relative;
}
.tooltip-top::before {
    content: attr(title);
    padding: 1rem 1.5rem;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%, -50%);
    width: 60px;
}
<a href="#" class="tooltip-top" title="content">Tooltip</a>
fiter
  • 633
  • 9
  • 20