articles » current » css » expanding-search-bar

CSS: Expanding Search Bar

HTML and CSS only!

This is a working search box that expands when in use. It requires only HTML and CSS — no JavaScript. The end-user can tap the search button to expand the search box or simply hover over it.

<!DOCTYPE html>
<html lang="en">
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	body {
		padding: 0;
		margin: 0;
		font-family: sans-serif;
		background-color: white;
	.search-icon::before {
		width: 100%;
		height: auto;
	main {
		display: flex;
		height: 100vh;
		justify-content: center;
		align-items: center;
	.search-box {
		display: inline-flex;
		padding: 2px;
		border: 2px solid slategray;
		outline: none;
		border-radius: 30px;
	.search-box:focus-within { /* IE11 WILL IGNORE BECAUSE IT IS NOT SUPPORTED */
		border-color: dodgerblue;
	.search-box input {
		outline: none;
		border: none;
		width: 0;
		background-color: transparent;
		color: black;
		font-size: 16px;
		padding: 0;
		transition: width .4s cubic-bezier(0.18, 0.89, 0.32, 1.33);
	.search-box input::placeholder {
		color: lightgray;
	.search-box:hover input,
	.search-box input:focus,
	.search-box input:valid {
		margin-left: 5px;
		width: 250px;
	.search-box button {
		outline: none;
		border: none;
		cursor: pointer;
		background-color: slategray;
		padding: 8px;
		width: 40px;
		height: 40px;
		border-radius: 50%;
		-webkit-appearance: none;
	.search-box:focus-within button { /* can't combine selectors here because IE11 will whine */
		background-color: red;
	.search-box input:focus + button {
		background-color: red;
	.search-box input:valid + button {
		background-color: limegreen;
			<form action="" class="search-box">
				<input type="text" name="q" autocomplete="off" autocapitalize="off" placeholder="enter search" required />
				<button type="submit"><i class="search-icon"></i></button>

Coding Video

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.