ページローディングのプログレスバーをCSSアニメーションで実装する
ページローディングのプログレスバーをCSSアニメーションで実装する方法です。少しのコードで表現できるので実装の手間はかからず予算少なめの案件でも提案しやすいのでおすすめです。
See the Pen Loading animation by MxGRAIN ( @mxgrain ) on CodePen .
.opening::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background-color: #111;
animation: opening 2.1s forwards;
}
@keyframes opening {
99% {
opacity: 1;
z-index: 1;
}
100% {
opacity: 0;
z-index: -1;
}
}
疑似要素
.opening::before
でローディング時の背景(デモの場合黒背景)を表示します。
width: 100%
と
height: 100vh
で全画面表示、
background-color: #111
で背景色指定。
animation: opening 2.1s forwards
の
opening
で、その下の
@keyframes opening
のプロパティを適用します。ローディング時間の99%までは
opacity: 1; z-index: 1;
、100%で
opacity: 0; z-index: -1;
に変化させます。
z-index: -1
を指定しないと、ページ全体に透明なフィルターをかけた状態になり、リンクやボタンのクリック、テキストの選択などアクションを起こせなくなりますので、下の階層へ下げます。
また、
animation
の
forwards
でアニメーション完了時のスタイルがアニメーション完了後にも適用されるので指定しています。
.opening::after {
content: '';
position: fixed;
top: 0;
left: 0;
width: 0;
height: 10px;
background-color: #d3ac07;
animation: openingline 2s forwards;
}
@keyframes openingline {
99% {
width: 0;
opacity: 1;
z-index: 1;
}
100% {
width: 100%;
opacity: 0;
z-index: -1;
}
}
疑似要素
.opening::after
でローディング時のラインアニメーションを表現します。
top: 0
で画面上部に配置、
left: 0
が開始位置です。99%まで
width: 0; opacity: 1; z-index: 1;
、100%で
width: 100%; opacity: 0; z-index: -1;
と変化。これで画面上部の左から右へアニメーションしていき、完了後は非表示にしています。
こちらも
z-index: -1
と
animation: forwards
を指定し、ラインを非表示にしています。