关键是通过公式进行边距的过渡。如果它被浮动,过渡期间会有一点令人讨厌的“摇晃”。
编辑添加选项
选项1: 在保留空间内展开
http://jsfiddle.net/xcWge/14/:
#square {
width: 10px;
height: 10px;
margin: 100px;
-webkit-transition: width 1s, height 1s, margin 1s;
-moz-transition: width 1s, height 1s, margin 1s;
-ms-transition: width 1s, height 1s, margin 1s;
transition: width 1s, height 1s, margin 1s;
}
#square:hover {
width: 100px;
height: 100px;
margin: 55px;
}
选项2:在其周围扩展元素 http://jsfiddle.net/xcWge/18/:
#square {
width: 10px;
height: 10px;
margin: 0;
-webkit-transition: width 1s, height 1s, margin 1s;
-moz-transition: width 1s, height 1s, margin 1s;
-ms-transition: width 1s, height 1s, margin 1s;
transition: width 1s, height 1s, margin 1s;
}
#square:hover {
width: 110px;
height: 110px;
margin: -50px;
}
选项3:在流中扩展其前面的元素并移动其后面的元素 http://jsfiddle.net/xcWge/22/。
#square {
width: 10px;
height: 10px;
margin: 0;
position: relative;
top: 0;
left: 0;
-webkit-transition: width 1s, height 1s, top 1s, left 1s, margin 1s;
-moz-transition: width 1s, height 1s, top 1s, left 1s, margin 1s;
-ms-transition: width 1s, height 1s, top 1s, left 1s, margin 1s ;
transition: width 1s, height 1s, top 1s, left 1s, margin 1s;
}
#square:hover {
width: 110px;
height: 110px;
top: -50px;
left: -50px;
margin-right: -50px;
margin-bottom: -50px;
}
添加一个非正方形的示例
有人评论说这对于非正方形(宽度/高度不同)不起作用,但这只意味着在过渡期间必须针对每个方向进行不同的调整。因此,这里是选项2(包括非正方形),它从矩形开始,在过渡期间宽度扩展的比高度多两倍(因此甚至会改变矩形形状):在周围元素上扩展http://jsfiddle.net/xcWge/2131/
#rectangle {
width: 110px;
height: 10px;
margin: 0;
-webkit-transition: width 1s, height 1s, margin 1s;
-moz-transition: width 1s, height 1s, margin 1s;
-ms-transition: width 1s, height 1s, margin 1s;
transition: width 1s, height 1s, margin 1s;
}
#rectangle:hover {
width: 310px;
height: 110px;
margin: -50px -100px;
}
如果只有width
从110px变为210px这样变化了100px,那么margin: -50px
仍然可以正常工作。