htmlcss

Moving an div from the top left corner to bottom right using css


I am trying to move a div from top left corner to bottom right corner using only CSS (this is required for my assignment). Also, I need to see the transition happening (the div sliding to the bottom). I tried using transform:translate() but i can't get my div to go to the bottom corner! Here is what I've done until now: http://codepen.io/ascii-hero/pen/JXEXVB


Solution

  • Tldr;

    Solution 1: Using Left/Right/Top/Bottom positioning

    In order for your div to move, you will need to set a parent element to relative, and the div to absolute positioning. Note, since the html element is the 'top most' element of the html tree, it is automatically assumed this relative position.

    div {
      background: red;
      height: 50px;
      width: 50px;
      position: absolute;
      top: 0;
      left: 0;
    }
    html:hover div {
      top: auto;
      left: auto;
      bottom: 0;
      right: 0;
    }
    <div></div>


    Solution 2: Transforms

    Using transforms is great, as you can also add transitions for a smooth effect. Just note you'll need to add just a slight alteration to solution 1.

    div {
      background: red;
      height: 50px;
      width: 50px;
      position: absolute;
      top: 0;
      left: 0;
      transition: all 0.4s;
    }
    html:hover div {
      top: 100%;
      left: 100%;
      transform: translate(-100%, -100%);
    }
    <div></div>

    Explanation of Solution 2

    To allow for transforms, the DOM needs to know the start point, the end point, and the duration explicitly. So hence, the start is set to

    top:0; left:0;
    

    To represent the top and left vales.

    The 'duration' can be set using the transition property. Here I have set this to 0.4s(econds), but this can be altered to any suitable value.

    Lastly, and most crucially, you need to set a definitive end point to your transform. Here you will notice the

    top:100%;left:100%; 
    

    However, as I am sure you are aware in doing that it will put the very top left corner at this position, (100%,100%) so to speak. It is hence the reason for the inclusion for the translate to 'move the box back onto the screen'. The translate property takes two values, the X and Y disposition. By using a % as the unit, it will move a % of the size of either the width or height of the box, depending on the axis you are moving it. In other words, using

    transform:translate(-100%, -100%);
    

    will move the box 100% (of itself) to the left, and 100% (of its height) up, hence it can be seen in the bottom right of the page.