Let’s have a look at how to add an animation effect to a search icon using CSS transition.

It’s essential to have icons designed in a same style when you build a website. Consistency is the key for a good design, and icons are not an exception. So we will make a search icon same style as the burger menu icon here. The process is almost identical.

Firstly, we need to create a search icon using HTML and CSS.

1
2
3
4
<div class="search-button">
  <div class="search-icon">
  </div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
.search-button {
  width: 100px;
  height: 100px;
  background-color: DeepSkyBlue;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
}
.search-button::before {
  content: "";
  position: absolute;
  top: 22.5%;
  right: 23.5%;
  width: 0;
  height: 4px;
  margin-top: -2px;
  background-color: #ffffff;
  transform: rotate(-45deg);
  transform-origin: right top;
}
.search-button::after {
  content: "";
  position: absolute;
  bottom: 22.5%;
  right: 23.5%;
  width: 30%;
  height: 4px;
  margin-top: -2px;
  background-color: #ffffff;
  transform: rotate(45deg);
  transform-origin: right bottom;
}
.search-icon {
  position: absolute;
  display: block;
  top: 20%;
  left: 20%;
  width: 35%;
  height: 35%;
  border-radius: 50%;
  border-width: 4px;
  border-style: solid;
  border-color: #ffffff;
}

There we have a search icon. Now let’s make it turn into a close icon ‘X’ using CSS and jQuery. With jQuery we will add ‘active’ class to the ‘.search-button’ when clicked.

1
2
3
$(".search-button").click(function() {
  $(this).toggleClass("active");
});
44
45
46
47
48
49
50
51
52
.search-button.active::before,
.search-button.active::after {
  width: 77.5%;
}
.search-button.active .search-icon {
  width: 0;
  height: 0;
  border-color: transparent;
}

When you click the search icon, it should turn into an ‘X’ close icon. However, it’s not animating yet. What we need to add is the CSS transition, my absolute favourite CSS ingredient. Add the line 58-61 for the colour transition effect.

53
54
55
56
57
58
59
60
61
.search-button::before,
.search-button::after,
.search-button .search-icon {
  transition: all 0.3s ease-in-out;
}
.search-button.active,.search-button:hover {  background-color: RoyalBlue;}

The result

There you have it, the search icon css animation. You can also see it in action at my CodePen page.

See the Pen Search Icon CSS Animation by Web Made Well (@webmadewell) on CodePen.32161