Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Cách dùng CSS Animations xoay Images liên tục

Trong quick tutorial này, bạn sẽ học cách continuously rotate images dùng CSS animation property.

Đầu tiên, cần HTML markup với image và attributes:

<img src="https://vn.wsxdn.com/UploadFiles_2724/202203/2022033109325250.png" class="rotate linear infinite" width="150" height="150" />

Image nên show up như sau:

Cách dùng CSS Animations xoay Images liên tục

Như bạn thấy image element có ba classes: rotate, linear và infinite. Trong CSS stylesheet cần tạo declaration block cho mỗi class. Loại classes này đôi khi gọi utility hoặc helper classes, nhưng tôi thích term single-purpose vì descriptive hơn.

Đầu tiên declare .rotate code block:

.rotate { animation: rotation 2s; }

Chưa có gì xảy ra, vì cần define animation property's rotation function. Thêm CSS keyframe rule này vào stylesheet:

@keyframes rotation { from { transform: rotate(0deg); } to { transform: rotate(359deg); } }

Bây giờ reload browser tab, bạn nên thấy image rotate một lần trong 2 giây (2s). Nhưng cần làm hai điều nữa. Muốn image rotate continuously, và đổi animation transition timing từ default ease sang consistent speed curve tên linear.

Thêm .linear declaration block vào CSS stylesheet:

.linear { animation-timing-function: linear; }

Reload browser tab, bạn thấy image spin ở consistent speed rate từ start đến end.

Cuối cùng, làm image rotate infinitely bằng cách declare .infinite class code block:

.infinite { animation-iteration-count: infinite; }

Và voila, bạn có infinitely/continuously spinning image với linear animation speed curve.

Cách dùng CSS Animations xoay Images liên tục

Xem complete code trên CodePen

Lưu ý: chúng ta có thể declare tất cả animation properties trong single line và single class, như sau:

.rotate-image { animation: rotation 2s linear infinite; }

Trên tiết kiệm nhiều code, nhưng cho learning/teaching, tôi prefer break things down thành smaller bites, vì dễ hiểu individual components work together như thế nào.

Có nhiều animation curves bên cạnh default ease và linear dùng ở đây. Bạn có thể get fancy với cubic-bezier animation curve, nhưng tôi save cho tutorial khác.