CSS: Make a search field with a magnifying glass icon inside

Updated: February 23, 2022 By: A Goodman 6 comments

This is a short and straight-to-the-point guide on how to make a search filed with a magnifying glass icon inside from scratch without using any third-party library. Here’s what you’ll see at the end:

Getting Started

1. Create a new folder called example or whatever you like (the name doesn’t matter). In this folder, create 2 files: index.html and style.css.

2. Download the following PNG image to the example folder (you can use another png file if you want):

Our folder structure at this point:

.
├── index.html
├── search.png
└── style.css

3. HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Search Field</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <form action="/" method="GET" class="form">
        <input type="search" placeholder="Search" class="search-field" />
        <button type="submit" class="search-button">
          <img src="search.png">
        </button>
      </form>
    </div>
  </body>
</html>

4. CSS code:

* {
  /* Reset browser's padding and margin */
  margin: 0;
  padding: 0;
  box-sizing: border-box; 
}

body {
  background: #4a69bd;
}

.container {
  margin: 200px auto;
  width: 500px;
  height: 60px
}

/* The point of this tutorial is here */
.form {
  display: flex;
  flex-direction: row;
}
.search-field {
  width: 100%;
  padding: 10px 35px 10px 15px;
  border: none;
  border-radius: 100px;
  outline: none;
}

.search-button {
  background: transparent;
  border: none;
  outline: none;
  margin-left: -33px;
}

.search-button img {
  width: 20px;
  height: 20px;
  object-fit: cover;
}

That’s it. Further reading:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
6 Comments
Inline Feedbacks
View all comments
Ellaoui
Ellaoui
1 year ago

It’s amazing thank you! How did you make it so that the “x” that removes the content in the input shows up? I cant see it written anywhere?

Akhter jafarinejad
Akhter jafarinejad
2 years ago

Drive salted and save

Anon
Anon
2 years ago

Thank you very much 🙂 This is great!

Steve
Steve
2 years ago

Thank you so much for the guide!

Related Articles