Building a Custom Search Field with HTML and CSS

Author

Reads 1.3K

A white stork searches for food in a grassy field, captured with warm lighting.
Credit: pexels.com, A white stork searches for food in a grassy field, captured with warm lighting.

Building a custom search field with HTML and CSS requires a basic understanding of HTML structure and CSS styling. You can create a simple search field by using an input field with a type attribute set to "search".

To add a placeholder text to the search field, you can use the placeholder attribute in the input field. This will display the text inside the input field until the user starts typing.

A CSS style can be used to change the appearance of the search field, such as its width, height, and background color. For example, you can use the width property to set the width of the search field to 200 pixels.

You can also add a CSS style to change the color of the placeholder text. For instance, you can use the color property to set the color of the placeholder text to blue.

Check this out: Html Placeholder

HTML Structure

The HTML structure of a search field is quite straightforward. It's just a simple div containing an input element and a button. The input element should have a type attribute equal to "search" to ensure better usability on mobile devices.

Check this out: Html B Tag

Credit: youtube.com, How to make a search bar using html and css in 10 just minutes

A search input field is functionally identical to a text input field, but using the "search" type is semantically correct. This is because it's designed for the user to enter search queries into.

The HTML for our search box with an icon consists of a form, input, and button elements. The form acts as a wrapper and will react to the submit event.

To improve usability, you can specify an input placeholder, such as "Search…", to give the user a hint that this is indeed a search input. This is a good practice to follow.

The button should have a type attribute equal to "submit" to ensure the form can be submitted via button click without additional events for this button.

Styling with CSS

Styling with CSS is a crucial part of creating a visually appealing search field. To make your search field stand out, you can use CSS to customize its appearance.

Credit: youtube.com, Creating a Stylish Search Bar for Your Website: HTML & CSS Tutorial

To start, you'll want to set the display property of the form element to flex, allowing you to properly align input and button elements. You can also set a border property to wrap elements closer together. This makes it easier to style your search field and create a cohesive look.

The search input box should span the full width of the container element and have visually appealing properties. You can use a combination of CSS properties, such as width, height, padding, and background color, to achieve this. For example, you can set the width to 100% and the height to 50px, and add some padding to create space between the input and the button.

To display a magnifying glass icon on the submit button, you can use encoded SVG as a background image. This adds a touch of elegance to your search field and makes it more user-friendly.

Intriguing read: Html Property Attribute

Differences Between

Some browsers show a cross icon that can be clicked on to remove the search term instantly if desired, in Chrome this action is also triggered when pressing escape.

Credit: youtube.com, CSS Absolute vs Relative Position EXPLAINED!

Modern browsers automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain.

You can provide a useful placeholder inside your search input that could give a hint on what to do using the placeholder attribute.

Browsers handle search and text types differently, and some browsers render placeholders in a specific way.

The cross icon can be clicked to remove the search term instantly, and some browsers also trigger this action when pressing escape.

Input Value Length

You can specify a minimum length for the entered value using the minlength attribute, and a maximum length using the maxlength attribute.

The minlength attribute sets the minimum number of characters required for the entered value, as seen in the example that requires 4-8 characters in length.

If you try to submit a form with less than 4 characters, you'll be given an error message that differs between browsers.

Trying to go beyond 8 characters in length will prevent the browser from letting you submit the form.

Intriguing read: Html Utf 8 Character Set

Customizing the Search Field

Credit: youtube.com, How To Make A Search Bar Using HTML And CSS In 10 Just Minutes

To customize the search field, you can use the ::-webkit-search-cancel-button pseudo element to style the delete button. This is especially useful for Chrome and Safari, where the default style is inconsistent with the rest of your web app's design.

The default style of the delete button can be removed with -webkit-appearance: none;, and then you can use properties like background, height, and width to shape your own delete button.

You can also use an SVG image of the cross icon from Material Icons and edit its color with fill="rgb(148, 148, 148)". To convert the SVG code into a Data URL, use the URL-encoder for SVG.

Here are some key properties to style the search box text:

These properties will help you style the search box text and placeholder text consistently across browsers.

Lit-Node 1 Maxlength

The Lit-Node 1 Maxlength attribute is a crucial setting for your search field. It specifies the maximum length of text that can be entered into the field.

Credit: youtube.com, HTML Web Design Tutorials: HTML Max Length Attribute for Input Fields Lesson 32

The input will fail constraint validation if the length of the text entered is greater than maxlength UTF-16 code units long. This means that if you set a maxlength of 10, for example, the user won't be able to enter more than 10 characters.

Constraint validation only applies when the value is changed by the user, so if the user types in 10 characters and then changes the value to 9, the input won't fail constraint validation.

6. Style Sub-Components

One of the most important aspects of customizing the search field is styling its sub-components. You can use the descendant combinator to define styles for a subcomponent of the search box, as seen in Example 3.

The descendant combinator is a shorthand way of writing CSS selectors, making it easier to style sub-components. For instance, instead of assigning a class to each sub-component, you can use .searchbox > * to define styles for all elements inside the search box.

Check this out: Components of Html

A gray squirrel searches for food in a snowy field during the winter season.
Credit: pexels.com, A gray squirrel searches for food in a snowy field during the winter season.

Here's a breakdown of the descendant combinator syntax:

  • `>` denotes a direct child
  • `*` is a wildcard that matches any element

Using this syntax, you can create more readable and maintainable CSS code. For example, you can use `.searchbox > .icon` to define styles for the icon inside the search box.

By styling sub-components, you can create a more cohesive and visually appealing search field. Remember to use the descendant combinator to make your code more efficient and easier to manage.

No Button Example

The No Button Example is a great way to customize your search field. You can remove the submit button from the form and leave existing form and input styles.

Just set the icon as a background for the input, which is a simple and effective way to display an icon inside an input without it being a button.

SVG Icon and Input Elements

Wrapping the SVG icon and input elements with a div is essential for creating a visually appealing search field. This is done by placing a relatively positioned div element around the input and SVG elements, with a class name of searchbox.

Credit: youtube.com, Icon inside input field

To ensure the SVG icon is rendered beneath the search box, the z-index of the SVG element needs to be set to -1, allowing it to go beneath all child elements of the div.

The input element, however, has a white background by default, which hides the SVG element beneath. To fix this, the background of the input element needs to be made transparent.

SVG Magnifying Glass Icon

When designing an SVG magnifying glass icon, consider adding aria-hidden="true" to the code. This is because screen reader users already know what the icon represents, thanks to the aria-label attribute value of the associated input element.

You can create an SVG magnifying glass icon using code, as shown in Example 1. Adding aria-hidden="true" simply means you don't need to tell screen reader users about the icon's presence.

Recommended read: Aria-label Html

Input Demo

For the Input Demo, you'll mainly use CSS to make it functional, along with some HTML and JavaScript.

Credit: youtube.com, How to Incorporate Icons Inside Input Elements in a Form

The demo showcases the final result, giving you an idea of what to aim for with your own project.

Using a combination of HTML, CSS, and JavaScript, you can create a search input demo that's both functional and visually appealing.

Check out the demo to see how the different elements come together to create a seamless user experience.

With the right combination of code, you can create an input demo that's both easy to use and visually stunning.

Text and Icon Styling

The magnifying glass icon looks best when it's sized three-quarters of the search box's height. This is a key detail to get right for a visually appealing search field.

To match the icon color with the search box border, use the fill property. The icon color should also match the search box border color.

The text color should be set so it will match the icon color as well as the search box border color. This creates a cohesive look for the search field.

Customizing Text Delete Button Style for Chrome and Safari

Credit: youtube.com, How to Add Text to a Button with an Icon in HTML and CSS

Customizing the text delete button style for Chrome and Safari can be a bit tricky, but it's definitely doable. The default style of the delete button differs between Chrome and Safari, and it's inconsistent with the rest of your web app's design.

To customize the style of the delete button, you can use the ::-webkit-search-cancel-button pseudo element. This is a handy trick that Coyier (2010) first discovered.

You'll need to remove the browser's default style with -webkit-appearance: none; to make way for your own custom design. Then, you can use the background, height, and width properties to shape your own delete button.

Using an SVG image of the cross icon from Material Icons is a great way to add some visual flair to your delete button. You can edit the SVG code to change the color of the icon, just like I did with fill="rgb(148, 148, 148)".

To use the SVG image as a background-image value, you'll need to convert it into a Data URL using a URL-encoder for SVG. This might seem like a lot of work, but it's worth it for the custom look and feel of your delete button.

On iOS Safari, the search box will flash a grey background when the user taps it, which can be a bit annoying. To disable this feature, you can use an obscure Webkit-specific CSS property, but don't worry, it's easy to find.

Here's an interesting read: Ipad Open Html File in Safari

Border and Width

A peaceful rural scene featuring a tractor working in a vast agricultural field under a blue sky with clouds.
Credit: pexels.com, A peaceful rural scene featuring a tractor working in a vast agricultural field under a blue sky with clouds.

A 1px border is too thin for the user to notice the search box, so it's best to set the border width to 2px. This thickness strikes a balance between visibility and sophistication.

The search box's shape can be replicated by using semi-circles on both sides, achieved by setting the border-radius to half the height of the box.

Drawing the Border

A 2px border width is ideal for a search box, as it's thin enough to be noticeable but not so thick that it looks unsophisticated.

The shape of the border is also important, and to replicate Google's search box, you'll want to create semi-circles on both sides of the box by setting the border-radius to half the height of the box.

This value can be defined as a CSS variable, which is useful if you plan to use it for another purpose later.

Focus and Spacing

When designing a search field, you want to make sure the input area is large enough to hold the user's search query. A good rule of thumb is to set the width of the input field to at least 200 pixels.

Credit: youtube.com, How to create an expanding search bar using :focus-within

To create a visually appealing search field, you can use the padding property to add some space between the input field and its border. For example, setting padding to 10px can help create a comfortable buffer between the input field and its border.

The margin property can also be used to add space around the search field, making it easier to read and use. By setting margin to 10px, you can create a clean and uncluttered layout.

Styling the Focus Ring

Styling the focus ring can be a bit tricky, but it's doable with the right combination of properties. To make the focus ring glow, you can use the combination of border and box-shadow.

Explicitly styling the outline property has an additional benefit: it removes the browser's default focus ring, which is usually done with outline: none.

In order to avoid issues with Forced Color Modes, it's a good idea to add a transparent outline as a fallback, as Soueidan recommends. This will remove the focus ring styled with background, border, and/or box-shadow properties.

By styling the focus ring with properties other than outline, you can achieve the desired effect, but don't forget to add that transparent outline for Forced Color Modes.

Intriguing read: Focus Html Element Js

7.3 Vertical Spacing

A tranquil dirt road winds through a lush green forest and vibrant field of yellow flowers under a clear sky.
Credit: pexels.com, A tranquil dirt road winds through a lush green forest and vibrant field of yellow flowers under a clear sky.

Vertical spacing is crucial for creating a balanced and visually appealing design.

The relatively-absolute positioning technique is a viable alternative to flexbox for vertically center-aligning items.

Setting the top and bottom values to be equal is the key to achieving this alignment.

Flexbox is often the easiest way to vertically center-align items, but it may not be the best choice in every situation.

The search box icon in Example 1 is vertically center-aligned using the relatively-absolute positioning technique.

Cory Hayashi

Writer

Cory Hayashi is a writer with a passion for technology and innovation. He started his career as a software developer and quickly became interested in the intersection of tech and society. His writing explores how emerging technologies impact our lives, from the way we work to the way we communicate.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.