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):
top: 50%
to top: 0
. Result: top 50% of div is off the screen; top: 50%
to top: 0
. Result: 50% of div is off the screen at right; top: 50%
to top: 43%
. Result: div aligned top; top: 50%
to top: 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?
It's working like that because you are changing the coordinates of the object with the translateY property. If you delete all of the translateY properties or set them to 0 like this: translateY (0);
and add top:0;
it will align to the top of the window.
You can read more about how translate works here: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate
Here's how your css should look:
.container {
position: absolute;
top: 0;
left: 50%;
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.