A search bar is an essential element on web pages, acting as the gateway between the user and the site content they are seeking. It's a text field where users can type a search term and submit it to a search engine or a website's internal search functionality. The search bar fills a crucial role in user experience, allowing for quick navigation to the desired information without sifting through pages of content.
In web design, a search bar is not just a convenience—it's a necessity. It allows users to bypass the navigation bar and directly access the information they need. A well-designed search bar can enhance the usability of a site, making it more user-friendly and efficient. For instance, a search bar that offers suggestions as the user presses keys can significantly streamline the search process.
<input>
ElementThe <input>
element is one of the most versatile HTML elements. It is used to create a variety of user input fields, where the user can enter data. This data can be text, numbers, passwords, and more. The <input>
tag is a self-closing tag, which means it does not need a closing tag. It is always nested within a <form>
element, which defines how the information will be submitted. The <input>
element's behavior and appearance are largely determined by its attributes, including type, name, placeholder, and value.
To create a search bar, we start with the basic HTML code that includes a form element and an input field. Here's a simple example of how to create a search bar using HTML:
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Simple Search Bar</title> 6</head> 7<body> 8 <form action="/search" method="get"> 9 <label for="site-search">Search the site:</label> 10 <input type="search" id="site-search" name="q" aria-label="Search through site content"> 11 <button type="submit">Search</button> 12 </form> 13</body> 14</html>
In this code snippet, we have a form with an action attribute that points to the URL where the search query will be processed, typically a server-side script like PHP. The method attribute is set to "get", meaning the search terms will be sent as URL parameters. The input element has the type attribute set to "search", making it a dedicated search field. We also include an id for the input, which is referenced by the label tag's for attribute, improving accessibility. The aria-label attribute further enhances accessibility, describing the input's purpose for screen readers.
This basic structure lays the foundation for a functional search bar, which we will style and enhance in the following sections.
CSS, or Cascading Style Sheets, is the language used to add style to HTML documents. It controls the visual presentation of HTML elements, allowing you to set the layout, colors, fonts, and much more. By separating the content (HTML) from the design (CSS), you can create rich, visually engaging web pages that are also easy to maintain and update.
A search bar should be both functional and visually appealing. Here's how you can use CSS to enhance the appearance of your search bar:
Size and Padding
The size of the search bar should be large enough to be easily clickable, and padding can be added to ensure the text inside the input box is not cramped. Here's an example of CSS that adjusts these properties:
1input[type="search"] { 2 width: 100%; 3 padding: 8px; 4}
Borders give definition to the search input, and outlines can be used to highlight the search bar when it's active. Here's a CSS rule that styles the borders and outlines:
1input[type="search"] { 2 border: 2px solid #ccc; 3 outline: none; 4} 5 6input[type="search"]:focus { 7 border-color: #228B22; 8 outline: none; 9}
The background color can be set to match your site's theme, and a background image, such as a magnifying glass icon, can be added to the search input to indicate its function. Here's how you can style the background:
1input[type="search"] { 2 background-color: #f9f9f9; 3 background-image: url('search-icon.png'); 4 background-position: right 10px center; 5 background-repeat: no-repeat; 6}
The font size, color, and family used in the search bar should be readable and consistent with the rest of your site. Here's an example of text styling:
1input[type="search"] { 2 font-size: 18px; 3 color: #333; 4 font-family: Arial, sans-serif; 5}
A responsive search bar adjusts seamlessly to different screen sizes, ensuring a great user experience across all devices. Here are some tips to achieve this:
Use relative units like percentages for width and em or rem for padding and font size.
Employ media queries to adjust the style of the search bar for different screen resolutions.
Ensure that the search button and input field are easy to tap on touch screens by providing ample size and space.
Here's an example of a media query that increases the font size and padding on smaller screens:
1@media (max-width: 600px) { 2 input[type="search"] { 3 font-size: 18px; 4 padding: 12px; 5 } 6}
JavaScript is a powerful scripting language that enables you to create dynamic and interactive web pages. When combined with HTML and CSS, JavaScript can manipulate HTML elements, respond to user actions, and communicate with web servers, all in real-time. By using JavaScript, you can enhance the functionality of a search bar, making it more user-friendly and efficient.
Interactive features such as autocomplete and live search results can significantly improve the user experience. Autocomplete predicts what the user is typing and suggests possible completions, while live search results display potential matches before the search query is even submitted.
To add an autocomplete feature to your search bar, you can use JavaScript to detect user input and display a list of suggestions. Here's a basic example of how you might implement this:
1<input type="search" id="autocomplete-search" name="q" placeholder="Search..."> 2<div id="autocomplete-results"></div> 3 4<script> 5document.getElementById('autocomplete-search').addEventListener('input', function() { 6 var input = this.value; 7 // Perform a search or filter operation here, typically with AJAX 8 // For demonstration purposes, we'll use a static array of search terms 9 var searchTerms = ['HTML', 'CSS', 'JavaScript', 'PHP', 'Python']; 10 var results = searchTerms.filter(function(term) { 11 return term.toLowerCase().startsWith(input.toLowerCase()); 12 }); 13 14 // Display the results in the autocomplete-results div 15 var resultsDiv = document.getElementById('autocomplete-results'); 16 resultsDiv.innerHTML = ''; // Clear previous results 17 results.forEach(function(term) { 18 var div = document.createElement('div'); 19 div.textContent = term; 20 div.addEventListener('click', function() { 21 document.getElementById('autocomplete-search').value = term; 22 resultsDiv.innerHTML = ''; // Clear the results 23 }); 24 resultsDiv.appendChild(div); 25 }); 26}); 27</script>
In this example, as the user types into the search bar, an event listener triggers a function that filters a list of search terms based on the input. The matching terms are then displayed as clickable divs that populate the search input when clicked.
Live search results work similarly to autocomplete but typically involve querying a database and returning relevant results in real-time. This often requires server-side processing with AJAX to fetch the results without reloading the page. Here's a simplified example using JavaScript and AJAX:
1document.getElementById('live-search').addEventListener('input', function() { 2 var input = this.value; 3 if (input.length < 3) { // Minimum number of characters before searching 4 return; 5 } 6 7 // Use AJAX to query the server and get live search results 8 var xhr = new XMLHttpRequest(); 9 xhr.open('GET', '/search-results?q=' + encodeURIComponent(input), true); 10 xhr.onload = function() { 11 if (xhr.status === 200) { 12 var results = JSON.parse(xhr.responseText); 13 // Display the results in a dedicated results div 14 var resultsDiv = document.getElementById('live-search-results'); 15 resultsDiv.innerHTML = ''; // Clear previous results 16 results.forEach(function(item) { 17 var div = document.createElement('div'); 18 div.textContent = item.title; // Assuming the result has a title 19 resultsDiv.appendChild(div); 20 }); 21 } 22 }; 23 xhr.send(); 24});
In this JavaScript snippet, an event listener is attached to the search input. When the user types, an AJAX request is sent to the server with the current input value. The server then returns a list of search results, which are dynamically displayed on the page.
The search bar on a website is not just a standalone feature; it often serves as the front end of a more complex system involving server-side technologies. When a user submits a search query, the search bar needs to communicate with a server that processes the request. This server could be running any number of backend technologies such as PHP, Node.js, Python, or Ruby. The server-side script will then perform the search against a database or an external service and return the results to the user's browser.
The HTML <form>
element is designed to facilitate this communication between the client and the server. By setting the action attribute of the form, you specify the URL to which the form data should be sent. The method attribute determines how the data is sent. Here's a basic example of an HTML form configured to send a search query to a server:
1<form action="/search-results" method="get"> 2 <input type="search" name="query" placeholder="Search..."> 3 <button type="submit">Search</button> 4</form>
In this example, when the user submits the form, the browser sends a GET request to the /search-results URL with the search term included as a query parameter (e.g., /search-results?query=user+search+term).
The two most common methods for sending data to the server are GET and POST:
GET: This method appends the form data to the URL as query parameters. It is ideal for search forms because the resulting URL can be bookmarked or shared. GET requests are also more cacheable and loggable. However, they have limitations on the length of the data that can be sent and should not be used for sensitive data.
POST: This method sends the form data in the body of the HTTP request, not in the URL. It is suitable for large amounts of data and for sensitive information, as it is not displayed in the URL. POST requests are not cacheable or bookmarkable.
On the server side, you would have a script ready to process the POST request. For example, in PHP, you might access the submitted search term using $_POST['query'].
Choosing between GET and POST for a search form typically depends on the nature of the search and the user experience you want to provide. For most search functionalities, GET is the preferred method because it allows users to share and bookmark their searches.
A search bar can be much more than a simple text field. By adding placeholder text, default values, and custom search buttons, you can guide users and make the search experience more intuitive.
Placeholder text serves as a hint to the user about what to search for or the format to use. Default values can be used to pre-populate the search bar with common searches or the user's last search term. Here's how you can add placeholder text and a default value to your search bar:
1<input type="search" name="query" placeholder="Search for products, categories, and more" value="Sneakers">
In this example, "Search for products, categories, and more" is the placeholder text that will disappear when the user starts typing, and "Sneakers" is the default value that will appear when the page loads but can be cleared by the user.
Search buttons can be customized to match the style of your site and to make them stand out. You can change the text, add icons, or even replace the button with an image. Here's an example of a custom search button with an icon:
1<button type="submit" class="search-button"> 2 <img src="search-icon.png" alt="Search"> 3</button>
In the CSS, you might style this button as follows:
1.search-button { 2 background-color: #cfd48b; 3 border: none; 4 padding: 5px; 5 cursor: pointer; 6} 7 8.search-button img { 9 width: 12px; 10 height: 12px; 11}
With advanced CSS techniques, you can create a search bar that not only functions well but also becomes a focal point of your design.
Gradients can add depth, while shadows can provide a sense of elevation. Animations can draw attention to the search bar or provide feedback when a user interacts with it. Here's an example of CSS that applies these advanced styles:
1input[type="search"] { 2 background-image: linear-gradient(to right, #f6f6f6, #c6c4c4); 3 box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 4 transition: box-shadow 0.3s ease; 5} 6 7input[type="search"]:focus { 8 box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); 9}
In this CSS, a gradient is applied to the background of the search input, a shadow is added for depth, and a transition effect is used to animate the shadow when the input is focused.
Throughout this blog, we've explored the multifaceted nature of the search bar, from its basic HTML structure to the intricate enhancements possible with CSS and JavaScript. We've seen how a search bar can be more than just a functional element on a webpage; it can be a powerful tool to enhance user experience, accessibility, and the overall aesthetic of a site.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.