對于剪切動畫,使用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模擬,然后子元素使用絕對定位
/* 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); }
我們常用的方式:
dislay: inline-block
top: 50% + transform: tranlsateY(-50%)
display: flex
其余還有padding上下撐高
、display: table
、position + margin: auto
、絕對定位 + margin
等等,這些屬于不常用、特殊場景才能用、CSS3之前的hack方式,CSS3之后就不必使用這些來實現垂直居中,就不多說了。
其中display: flex
屬于萬金油,大多數場景可以直接用它,但還是有些特殊的場景不能用:
子元素需要文字截斷,為了兼容4.X的Android瀏覽器,必須使用其他方式(一般是transform)
子元素需要多行布局,4.x的Android不支持flex-wrap,不能多行布局
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
前端項目中初始化項目結構
使用js變量作用域遇到的bug
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com