Explain Codes LogoExplain Codes Logo

How to add a search box with icon to the navbar in Bootstrap 3?

html
responsive-design
form-handling
accessibility
Anton ShumikhinbyAnton Shumikhin·Jan 26, 2025
TLDR

To embed a search box into Bootstrap 3's navbar, there's a .navbar-form to use. Just pair a text input field with a button, which includes a search icon using .glyphicon-search.

<form class="navbar-form navbar-right" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search"> <span class="input-group-btn"> <button class="btn btn-default" type="submit"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> </form>

Pop this snippet in your navbar, and the streamlined search feature is good to go, utilizing Bootstrap's inbuilt styles and icons for a frictionless integration.

Adding the search box: step-by-step instructions

Let's walk through the process of adding, customizing, and styling a search box in your Bootstrap 3 navbar, ensuring it's smoothly blended with your UI.

Input and Placeholder

Incorporate input[type='search'] in your form to improve form handling and user's experience.

<input type="search" class="form-control" placeholder="Search">

Here's a little secret: your browser might add some sweet clear icons on search inputs.

To Collapse or not to Collapse

Mobile-first design is a trend we can't ignore. For smaller screens, Bootstrap 3's collapsible navbar can come to the rescue. Wrap your search form in a collapsible div and use glyphicons for that compact touch:

<div class="navbar-header"> <!-- button in disguise. It's actually a Transformer of links --> </div> <div class="collapse navbar-collapse" id="yourNavbar"> <!-- Autobots roll out!... sorry, navbar links and search form here --> </div>

Polishing your Design Aesthetics

Apply negative margins, discard border radii, and keep the background color of the search button in sync with the navbar for a polished appearance. Don't just style, Sytle.

The Art of Detailing: Advanced hints for an engaging UI

An engaging search box not only serves functionality but also delights the user.

Kiss-Keeping icon simple and sweet

With the Bootstrap's .input-group-btn class, the search icon will seat neatly and accessibly next to the input field:

<span class="input-group-btn"> <button class="btn btn-default" type="submit"> <!-- Icon moonlighting as a clickable area --> <span class="glyphicon glyphicon-search"></span> </button> </span>

Width-spread it strategically

Ensure your search box doesn't wrap or expand awkwardly with either an inline width or media queries:

@media (min-width: 768px) { .navbar-form .input-group { width: 250px; /* Width on diet. Adjust as necessary */ } }

Accessibility. Need I say more?

Add role="search" to your form, and aria-label to search inputs/buttons. Helping screen readers understand your content is just good karma.