對於剪切動畫,使用clip-path代替width/height,避免DOM重排致使性能太低。瀏覽器
.animate { width: 200px; height: 200px; background: #000; animation: 1s clip; } @keyframes clip { 0% { clip-path: inset(0 0 0 0); } 100% { clip-path: inset(0 100% 100% 0); } }
clip-path也能用來進行其餘規則/不規則圖形的剪切佈局
.clip { clip-path: polygon(0 100%, 50% 0, 100% 100%, 0 30%, 100% 30%); /* 多邊形 */ clip-path: circle(30px at 35px 35px); /* 圓形 */ clip-path: ellipse(30px 25px at 35px 35px); /* 橢圓 */ }
除了使用transform3d開啓gpu加速,還能夠使用will-change強制gpu加速優化動畫性能性能
.animate { width: 200px; height: 200px; background: #000; animation: 1s clip; will-change: clip-path; } @keyframes clip { 0% { clip-path: inset(0 0 0 0); } 100% { clip-path: inset(0 100% 100% 0); } }
使用padding模擬,而後子元素使用絕對定位flex
/* 1:1 */ .container { width: 200px; } .container:after { display: block; content: ' '; padding-top: 100%; } /* 16:9 */ .container { width: 200px; } .container:after { display: block; content: ' '; padding-top: calc(100% * 9 / 16); }
咱們經常使用的方式:優化
其他還有padding上下撐高
、display: table
、position + margin: auto
、絕對定位 + margin
等等,這些屬於不經常使用、特殊場景才能用、CSS3以前的hack方式,CSS3以後就沒必要使用這些來實現垂直居中,就很少說了。動畫
其中display: flex
屬於萬金油,大多數場景能夠直接用它,但仍是有些特殊的場景不能用:3d