How to create an animated search form with CSS?


A lot of websites these days have an animate search box on the home page itself. On placing the mouse cursor within the search box, the search box width increases to make it easier for users to search. Let us see how to create such animated search form with HTML and CSS.

Create the search form

Use the <form> element and place the input type text in it. Do not forget to mention an apt placeholder for the users to understand the purpose of the textbox −

<form>
   Search:
   <input type="text" name="search" placeholder="Search Here...">
</form>

Style the search box

The search box is styled like this. Also, the transition is set using the transition property on the width property. The transition timing function is set to ease-in-out i.e., a transition with a slow start and end −

input[type=text] {
   width: 170px;
   font-size: 16px;
   background-color: white;
   padding: 12px 20px 12px 40px;
   transition: width 0.4s ease-in-out;
}

Animate the search form

Using :focus selector, on setting the focus, the width will change to 100%. The :focus selector selects the element that has focus −

input[type=text]:focus {
   width: 100%;
}

Example

The following is the code creates an animated search form with CSS −

<!DOCTYPE html>
<html>
<head>
   <style>
      *{
         box-sizing: border-box;
      }
      input[type=text] {
         width: 170px;
         font-size: 16px;
         background-color: white;
         padding: 12px 20px 12px 40px;
         transition: width 0.4s ease-in-out;
      }
      input[type=text]:focus {
         width: 100%;
      }

   </style>
</head>
<body>
   <h1>Animated search form example</p>
   <form>
      Search:
      <input type="text" name="search" placeholder="Search Here...">
   </form>
</body>
</html>

Updated on: 14-Dec-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements