1

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):

  1. Change top: 50% to top: 0. Result: top 50% of div is off the screen;
  2. Delete all transforms, change top: 50% to top: 0. Result: 50% of div is off the screen at right;
  3. Change top: 50% to top: 43%. Result: div aligned top;
  4. Delete all transforms, change top: 50% to top: 43%. Result: 75% of div disappears bottom right.

Results of css tweaks

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?

plugincontainer
  • 630
  • 2
  • 9
  • 28
  • 1
    `top: 0; transform: translateX(-50%) translateY(0%)` *Top* is the position to it's closest positioned parent element, while translateY will translate according to it's own size – Amaury Hanser Mar 27 '19 at 17:53

1 Answers1

2

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%);
    }
Matthew T Rader
  • 176
  • 1
  • 9