aaronstacy
aaronstacy

Reputation: 6428

Vertical centering with `position: relative` and `top: 50%`

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?

Upvotes: 0

Views: 11659

Answers (1)

0b10011
0b10011

Reputation: 18795

First, you should use absolute positioning, with the .grid set to relative positioning. Then, set top, bottom, left, and right to 0 on the .spinner element. Since you have a fixed width/height, the positioning along with margin:auto; will center the element perfectly (example):

.grid {
    position:relative;
}
.spinner {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
    height: 3px;
    width: 3px;
    background-color: red;
}

table {
    width: 100%;
}

In response to your note at the end, no, it's not possible with static positioning of the .grid element (unless you add a wrapper within the .grid element). This is because the .spinner element has no way of knowing the height dimensions of the table without having a container of some sort with relative positioning (which is where position:relative; on the .grid element 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).

Upvotes: 3

Related Questions