I’m trying to vertically center the .spinner element in the following markup (fiddle):
<div class=grid>
<div class=spinner></div>
<table>
<tr><td>row 1 cell 1</td><td>row 1 cell 2</td></tr>
<tr><td>row 2 cell 1</td><td>row 2 cell 2</td></tr>
<tr><td>row 3 cell 1</td><td>row 3 cell 2</td></tr>
</table>
</div>
With the following styling:
.spinner {
position: relative;
top: 50%;
left: 50%;
height: 3px;
width: 3px;
background-color: red;
}
If I set the .spinner top property to some pixel value, the browser actually positions it according to the value, but if I try to set it to a percentage, it does not work.
How do I vertically center the .spinner element?
NOTE: I understand I could set the .grid position to relative and the .spinner position to absolute, but I’d prefer to keep the grid statically positioned. Is this possible without modifiying the .grid‘s styling?
First, you should use
absolutepositioning, with the.gridset torelativepositioning. Then, settop,bottom,left, andrightto0on the.spinnerelement. Since you have a fixedwidth/height, the positioning along withmargin:auto;will center the element perfectly (example):In response to your note at the end, no, it’s not possible with static positioning of the
.gridelement (unless you add a wrapper within the.gridelement). This is because the.spinnerelement has no way of knowing the height dimensions of the table without having a container of some sort with relative positioning (which is whereposition:relative;on the.gridelement comes in to play). You can work around this with negative margins or relative positioning all you want, but it will never be able to accommodate dynamic content (with the current set of browsers/standards).