Usually, when we don’t have the exact measure of span
, we can use the following technique:
First, let the div
with position:relative
, so we can leave the span
in absolute
in relation to this.
Then we hit the upper left corner at 50% and 50%, that is, starting in the middle.
How we want the center of span
in the center of div
, and not the "beak" of span
in the middle, we compensate by using a 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, may instead depend on the transform
, 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’re going to animate some property, remember to put Translate always before, otherwise the movement can stay out of center.
See the difference in 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>
excellent response, beyond what I expected!
– DiChrist