expanding/animating a div from center when width is 100%

6.3k views Asked by At

I have a div with a border and i used keyframes to expand it onload but I want it to expand from the center rather than left to right.

http://andylilien.com/index2015.html

the css:

.navback { 
position:absolute;
bottom:0px;
padding-bottom:-8px;
width:100%;
height:17px;
background-color:#FFF;
border-top: 1px solid #d0d0d0;
z-index:999;
}   
@-webkit-keyframes expandline{
0%{width:0%;}
50%{width:50%;}
100%{width:100%;}
}
.navback{
-webkit-animation:expandline 2s;
}
1

There are 1 answers

12
Palpatim On BEST ANSWER

Adjust the height and width as you are doing, but transform the element by positioning its left and top appropriately.

Also, you don't really need keyframe animations for this if you're using a common easing function or linear animation.

#expander {
  position:absolute;
  width: 0;
  height: 17px;
  background-color: #FFF;
  border-top: 1px solid red;
  z-index: 999;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  -webkit-animation: expandline 2s;
}

@-webkit-keyframes expandline{
  0%   { width:   0%; }
  50%  { width:  50%; }
  100% { width: 100%; }
}
<div id="expander"></div>

What's happening with the CSS:

  • Start the element off in it's initial position (fully styled and positioned, but with 0 width)
  • Add a transition to the element defining what attributes will transition, and how long the transition will take
    • Now any time one of the specified attributes changes, it apply a transition rather than instantly applying the change
  • Define a class that represents the final state of your element (fully styled and positioned, as in the initial state, but with the width you want)

The expanding from center behavior is the result of:

/* #expander will now be positioned relative to the nearest ancestor with a position other than `static`, or the `body` element if nothing else qualifies */
position: absolute;

/* The top of #expander will be 50% down the positioning context's height (i.e., the top of #expander is vertically centered in its parent) */
top: 50%;

/* The left of #expander will be 50% of the positioning context's width (i.e., the left of #expander is horizontally centered in its parent) */
left: 50%;

/* Translate #expander 50% of its own width to the left, and 50% of its own height in the up direction */
transform: translate(-50%, -50%);

Since we don't animate the transform, it continues to apply as defined in the initial rule: keep #expander vertically and horizontally centered in its parent, regardless of how tall or wide it is.

Now you just use whatever trigger is appropriate (you said you were using onload) to apply the expanded class and trigger the transition.

Hope this helps.