Crus4

logo

How to Add Search Bar in HTML


Adding a search bar to your HTML page is very important. With the help of search bar, users can reach to any page of your website by simply searching for a specific keyword.

To create a search bar on our HTML page we will use an HTML <input> Element along with different attributes. Here is an Example:

Example

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="/search" method="get">
    <!-- Search input will be added here -->
    <input type="search" name="q" placeholder="Search...">
    <button type="submit">Search</button>
</form>
</body>
</html>

Run this code on our code editor and it will appear like this on an HTML Page:

Code Explanation

In an above code the action attribute in the form element is set to " /search", which indicates where the search query is sent when the form is submitted. The input element with the type attribute creates a search input field, where an user can type any text to search for their query. The placeholder attribute gives the hint to the user, what they should enter in the search field.

How to Style a Search Bar in CSS

You can also add CSS to an HTML search bar to make it look stylish. Here is an example of how you can add CSS to HTML.

Example

<!DOCTYPE html>
<html>
<head>
<style>
form {
            text-align: center;
            margin-top: 20px;
        }

        /* Style for the search input */
        input[type="search"] {
            padding: 8px;
            width: 300px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
            outline: none;
        }

        /* Style for the submit button */
        button[type="submit"] {
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
        }

        /* Hover effect for the submit button */
        button[type="submit"]:hover {
            background-color: #0056b3;
        }
</style>
</head>
<body>
<form action="/search" method="get">
    <!-- Search input will be added here -->
    <input type="search" name="q" placeholder="Search...">
    <button type="submit">Search</button>
</form>
</body>
</html>

CSS Code Explained

CSS is used to style our HTML Page or any element. In an above code we have write a CSS code to style the search bar. First we targeted the form element and set it’s margin and set it align to center. After that we targeted the input element and set it’s padding, width, border etc. At last we targeted the button element to make it stylish and attractive.


Share This Post!

How to Add Search Bar in HTML

Leave a Reply

Your email address will not be published. Required fields are marked *