Swing Effect in CSS

Chathurangi Jayawardana
2 min readAug 14, 2022

Hi all,

CSS Swing effect can be used to move or move back and forth on an axis to an element. In this article you can learn that how to implement swing effect to images.

The main two parameters are used in swing animation. There are,

  • Transform − This parameter applies to 2d and 3d transformation to an element.
  • Opacity − This parameter applies to an element to make translucence.

We can implement swing Effect in below methods.

  1. Swing Image with CSS Animation

This is the implementation of swing image with CSS animation.

Index.html

<html>
<head>
<title>Swing Effect Animation</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<figure class="swing">
<img src="https://res-5.cloudinary.com/frame-destination/c_lpad,dpr_2.0,q_auto/v1/media/wysiwyg/flowers1.jpg?_i=AB" width="200" >
</figure>
</body>
</html>

styles.css

.swing {
animation: swing ease-in-out 1s infinite alternate;
transform-origin: center -20px;
float:left;
}
@keyframes swing {
0% { transform: rotate(6deg); }
100% { transform: rotate(-6deg); }
}
.swing:after{
content: '';
position: absolute;
width: 20px; height: 20px;
border: 1px solid #999;
top: -10px; left: 50%;
z-index: 0;
border-bottom: none;
border-right: none;
transform: rotate(45deg);
}
.swing:before{
content: '';
position: absolute;
width: 5px; height: 5px;
top: -14px;left: 54%;
z-index: 5;
border-radius: 50% 50%;
background: #000;
}

You can see the Swing Image with CSS Animation Demo here.

2. Simple Swing Animation

This is the implementation of simple swing animation.

Index.html

<html>
<head>
<title>Simple Swing Effect Animation</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<figure class="swing">
<img src="https://image.pngaaa.com/537/34537-small.png" width="200" >
</figure>
</body>
</html>

styles.css

@keyframes swing  {
20% { transform: rotate(10deg); }
40% { transform: rotate(5deg); }
60% { transform: rotate(0deg); }
80% { transform: rotate(5deg); }
100% { transform: rotate(10deg); }
}
.swing {
animation: swing 3s ease-in-out forwards infinite;
-webkit-animation: swing 3s ease-in-out forwards infinite;
-webkit-transform-origin: top center;
transform-origin: top center;
}

You can see the Simple Swing Animation Demo here.

Thank You!

--

--

Chathurangi Jayawardana

Software Engineer | Technical Writer | University of Moratuwa, Sri Lanka.