Nice expanding search bar without JavaScript
This is a simple expanding search bar without JavaScript and minimal code. This search bar will not bump other elements out of place either. Easily expands to the left or to the right. I have added comments to help walk you through where all of the things you probably care about are happening.
by Max Poshusta
HTML
<div class="parent">
<div>
Some other element that shouldn't move.
</div>
<div class="search-container">
<input class="searchBar" placeholder="Search" />
</div>
</div>
<div class="bootstrap-version">
See my bootstrap version of this same search bar which includes a button attached to the search bar by <a href="https://jsfiddle.net/maxshuty/eh710yn5/" target="_blank">clicking here</a>.
</div>
CSS
/*CSS for this fiddle only, you probably don't want this.*/
body {
padding: 3em;
font-family: Arial, Helvetica, sans-serif;
}
.search-container {
margin-top: -0.67em;
}
.bootstrap-version {
margin-top: 3em;
}
/*End fiddle only styles.*/
/*CSS to make the search bar not bump other elements out of place.*/
.parent {
position: relative;
}
.parent > div {
display: inline-block;
}
.search-container {
z-index: 9999;
position: absolute;
/*If you want the search bar to expand to the right then..*/
/*..then just set this to left instead.*/
right: 1em;
}
/*End CSS to prevent other elements from moving.*/
/*Expanding search CSS*/
.searchBar {
position: relative;
outline: none;
-webkit-appearance: textfield;
-webkit-box-sizing: content-box;
font-family: inherit;
font-size: 100%;
background: #ffffff;
border: solid 1px #ccc;
padding: 9px 10px 9px 10px;
width: 125px; /*The initial width before it expands.*/
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-transition: all .5s;
-moz-transition: all .5s;
transition: all .5s;
float: right;
}
.searchBar:focus {
width: 465px; /*The width it will exand to on focus*/
background-color: #fff;
border-color: #b01e21;
-webkit-box-shadow: 0 0 5px #b01e21;
-moz-box-shadow: 0 0 5px #b01e21;
box-shadow: 0 0 5px #b01e21;
}
.searchBar::-webkit-search-decoration,
.searchBar::-webkit-search-cancel-button {
display: none;
}
.searchBar:-moz-placeholder,
.searchBar::-webkit-input-placeholder {
color: #999;
}
/*End expanding search CSS.*/