当宽度为100%时,从中心扩展/动画div

时间:2015-06-18 22:28:36

标签: css3 keyframe

我有一个带边框的div,我使用关键帧来扩展它的载荷,但我希望它从中心而不是从左到右扩展。

http://andylilien.com/index2015.html

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 个答案:

答案 0 :(得分:5)

正如您所做的那样调整高度和宽度,但通过适当地定位左侧和顶部来transform元素。

此外,如果您使用的是常用缓动函数或线性动画,则实际上并不需要关键帧动画。

#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>

CSS发生了什么:

  • 在元素的初始位置(完全样式和定位,但宽度为0)启动元素
  • 向元素添加转换,定义要转换的属性以及转换需要多长时间
    • 现在,只要其中一个指定的属性发生更改,它就会应用转换而不是立即应用更改
  • 定义一个表示元素最终状态的类(完全样式化和定位,如初始状态,但具有您想要的宽度)

从中心行为的扩展是以下结果:

/* #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%);

由于我们没有为transform设置动画,因此它会继续按照初始规则中的定义应用:将#expander垂直和水平居中放置在其父级中,无论其高度或宽度如何。

现在你只需使用适当的触发器(你说你使用onload)来应用扩展类并触发转换。

希望这有帮助。

相关问题