Normally, when we do not have the exact measure of span
, we can use the following technique:
First, leave div
with position:relative
, so we can leave span
in absolute
in relation to this.
Then we hit the top left corner in 50% and 50%, that is, starting in the middle.
As we want the center of span
in the center of div
, and not the "beak" of span
in the middle, we compensate using transform(-50%,-50%)
div {
position:relative;
width:100px;
height:100px;
/* o float e o border é só para visualizar */
float:left;
border:1px solid red
}
div span {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
<div>
<span>T</span>
</div>
<div>
<span>E</span>
</div>
<div>
<span>X</span>
</div>
<div>
<span>T</span>
</div>
<div>
<span>O</span>
</div>
If you set the size of span
s, you can instead use transform
to use negative margins:
div { position:relative; width:100px; height:100px; float:left; border:1px solid red; }
div span {
position:absolute; display:block;
top:50%; left:50%; width:20px; height:20px;
margin:-10px 0 0 -10px; background-color:#f90;
}
<div><span></span></div>
<div><span></span></div>
<div><span></span></div>
<div><span></span></div>
Using animations:
If you are going to animate some property, remember to always translate before, otherwise the movement may be out of center.
See the difference of the order of transform
s:
@keyframes rotate1 {
0% { transform:translate(-50%,-50%) rotate( 0 ) }
100% { transform:translate(-50%,-50%) rotate( 360deg ) }
}
@keyframes rotate2 {
0% { transform:rotate( 0 ) translate(-50%,-50%) }
100% { transform:rotate( 360deg ) translate(-50%,-50%) }
}
div { position:relative; width:100px; height:100px; float:left; border:1px solid red;}
div span { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); }
#d1 span { animation:rotate1 2s infinite linear }
#d2 span { animation:rotate2 2s infinite linear }
<div id="d1"><span>Certo</span></div>
<div id="d2"><span>Argh!!!</span></div>