Transition div position from bottom to top of container

Viewed 5889

I'm trying to get an (absolutely positioned) div to transition from bottom: 0 to top: 0 of it's parent div. I can happily get it to transition from bottom: 0 to bottom: 10rem for example, but not to top: 0. Any ideas anyone? Please see the code example below and thanks in advance!

        .container {
            position: relative;
            height: 20rem;
            width: 20rem;
            border: solid blue 0.05rem;
        }

        .child {
            position: absolute;
            display: inline-block;
            height: 5rem;
            width: 5rem;
            background-color: red;
            bottom: 0;
            top: auto;
            transition: all 1s;
        }

        .child:hover {
            top: 0;
            bottom: auto;
        }
<div class="container">
  <div class="child"></div>
</div>

1 Answers

Use the The calc() CSS function, then :hover the parent not the child.

 .container {
            position: relative;
            height: 20rem;
            width: 20rem;
            border: solid blue 0.05rem;
        }

        .child {
            position: absolute;
            display: inline-block;
            height: 5rem;
            width: 5rem;
            background-color: red;
            top: calc( 100% - 5rem ); /*100% - height*/
            transition: all .3s ease;
            will-change: top;
        }

  .container:hover  .child{
            top: 0;  
        }
<div class="container">
  <div class="child"></div>
</div>

You can also use The transform CSS property to translate the child element.

 .container {
            position: relative;
            height: 20rem;
            width: 20rem;
            border: solid blue 0.05rem;
        }

        .child {
            position: absolute;
            display: inline-block;
            height: 5rem;
            width: 5rem;
            background-color: red;
            bottom: 0;
            transition: all .3s ease;
            will-change: bottom;
        }

.container:hover  .child{
    bottom: 100%;
    transform: translateY(100%)
}
 
<div class="container">
  <div class="child"></div>
</div>

Related