Reputation: 263
I want to have tooltips in my paragraph text. A box with helper text should appear on hover.
I found the following code (I removed the hover to keep things simple):
.para {
margin-top: 200px;
}
.tooltip1 {
color: blue;
position: relative;
}
.tooltip-text1 {
position: absolute;
bottom: 125%;
left: 50%;
margin-left: -60px;
background-color: yellow;
text-align: center;
padding: 10px;
}
<p class="para">Todas estas questões, devidamente <span class="tooltip1">devidamente ponderadas <span class="tooltip-text1">Realizar o download dos testes para as avaliações formativas</span></span> levantam dúvidas sobre se a expansão dos mercados mundiais nos obriga à análise dos relacionamentos verticais entre as hierarquias</p>
These lines do the work but I don't understand how:
position: absolute;
bottom: 125%;
left: 50%;
margin-left: -60px;
Why does changing the negative margin have an effect on the width of the box?
Upvotes: 1
Views: 1704
Reputation: 805
negative margin has nothing to do with the width of the box. the negative margin value is the half of the width of tooltip so it becomes centered (because the left
property is set to 50%
). you must specify the width of tooltip. also apply box-sizing: border-box;
to it so border and padding are considered in the overall width of the tooltip and it becomes perfectly centered. I edited your code, check it out to see how it works.
.para {
margin-top: 200px;
}
.tooltip1 {
display: inline-block;
color: blue;
position: relative;
}
.tooltip-text1 {
width: 160px;
position: absolute;
bottom: 125%;
left: 50%;
margin-left: -80px;
background-color: yellow;
text-align: center;
padding: 10px;
box-sizing: border-box;
----------
}
<p class="para">Todas estas questões, devidamente <span class="tooltip1">devidamente ponderadas <span class="tooltip-text1">Realizar o download dos testes para as avaliações formativas</span></span> levantam dúvidas sobre se a expansão dos mercados mundiais nos obriga à análise dos relacionamentos verticais entre as hierarquias</p>
Upvotes: 1
Reputation: 552
The key here is to understand positionings in CSS (absolute and relative). When you give an absolute position to an element it searches the DOM for a first non-static parent (for this example relative (tooltip1 ) ) then it attaches itself to it as if that parent(tooltip1) were its whole screen. The margin-left: -60px is just tweak the location of the tootip-text but the absolute-relative position combo will keep it sticking to its parent.
More indepth: https://dzone.com/articles/css-position-relative-vs-position-absolute
Upvotes: 1