stylesheet

2014-08-09

CSSを使用したローディングアニメーションのサンプル

画像を使わずにCSSで作成したローディングアニメーションのサンプル。
ChromeとFirefoxでは動いた。GIF作るより楽かも。


作り方:

HTML
<div class="loading">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

空のspanタグを並べる。


CSS
@-webkit-keyframes blink {
    from {opacity: 1;}
    to {opacity: 0;}
}

@keyframes blink {
    from {opacity: 1;}
    to {opacity: 0;}
}

.loading {
    display: inline-block;
}

.loading span {
    display: inline-block;
    background: #47585c;
    width: 3px;
    height: 16px;
    -webkit-animation: blink 500ms linear both infinite alternate;
    animation: blink 500ms linear both infinite alternate;
}

.loading span:nth-child(1n) {
    -webkit-animation-delay: 0ms;
    animation-delay: 0ms;
}

.loading span:nth-child(2n) {
    -webkit-animation-delay: 100ms;
    animation-delay: 100ms;
}

.loading span:nth-child(3n) {
    -webkit-animation-delay: 200ms;
    animation-delay: 200ms;
}

.loading span:nth-child(4n) {
    -webkit-animation-delay: 300ms;
    animation-delay: 300ms;
}

.loading span:nth-child(5n) {
    -webkit-animation-delay: 400ms;
    animation-delay: 400ms;
}

.loading span:nth-child(6n) {
    -webkit-animation-delay: 500ms;
    animation-delay: 500ms;
}

spanを時間差でアニメーションさせて完成。




バリエーション:

scss化していじりやすくしてみる。

@mixin loading($selector, $keyframes, $color, $width, $height, $duration, $child_size) {

    #{$selector} {
        display: inline-block;

        span {
            display: inline-block;
            background: $color;
            width: $width;
            height: $height;
            -webkit-animation: $keyframes $duration linear both infinite alternate;
            animation: $keyframes $duration linear both infinite alternate;
        }

        @for $i from 0 through $child_size {
            span:nth-child(#{$i + 1}n) {
                -webkit-animation-delay: #{$i * 100}ms;
                animation-delay: #{$i * 100}ms;
            }
        }
    }
}

@-webkit-keyframes blink {
    from { opacity: 1; }
    to { opacity: 0; }
}

@keyframes blink {
    from { opacity: 1; }
    to { opacity: 0; }
}

// ノーマル
@include loading('.loading', blink, #47585c, 3px, 16px, 500ms, 5);    

// 色違い
@include loading('.loading-alt', blink, #7a4171, 3px, 16px, 500ms, 5);

// でかい
@include loading('.loading-large', blink, #d3381c, 16px, 32px, 1200ms, 10);

// ドット
@include loading('.loading-dot', blink, #666, 2px, 2px, 800ms, 50);





参照

CSSアニメーション