Ages ago, I copied and pasted approach 1 from this answer by Josh Crozier to center a div vertically and horizontally:
.container {
width:100%;
position: absolute;
top: 50%;
left: 50%;
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
For result, see image, below left. But now I need the div to align top, instead of center/middle. I've tried 4 different changes to the css (see image):
- Change
top: 50%
totop: 0
. Result: top 50% of div is off the screen; - Delete all transforms, change
top: 50%
totop: 0
. Result: 50% of div is off the screen at right; - Change
top: 50%
totop: 43%
. Result: div aligned top; - Delete all transforms, change
top: 50%
totop: 43%
. Result: 75% of div disappears bottom right.
I'm happy that 3) worked. But I have no idea why 43% is the magic number. Maybe it isn't exactly. I arrived at it by trial and error, load and reload. Is there a better way to do it?