In this new article, you’ll learn how to create a cool and usable CSS search box using the HTML placeholder
attribute. For the browsers that don’t support this new HTML5 attribute, a fallback is created using Modernizr’s feature detection.
HTML search form structure
The form
element is used as the wrapper, while the two inputs are used as a search field and search button respectively.
The code
You may notice the placeholder
attribute, but just ignore it for now, as we will talk later about it. The reason why there are so many id
’s (instead of CSS3 advanced selectors as input[type="text"]
or input[type="submit"]
) is that I wanted this to degrade gracefully for older browsers.
Form wrapper styles
Below you can see the current result:
Inputs styles
Quick tip:
When adding float: left
to an element, there’s no need to add also display: block
. The last one it’s implied.
HTML5 placeholder attribute
This new HTML5 placeholder attribute shows a text in a field as long as the field is empty and not focused, then hides the text. You surely have seen this technique before with JavaScript!
Browser support:
- Firefox 3.7+
- Safari 4.0+
- Chrome 4.0+
- Opera 11+
- IE10+
Fallback support
For web browsers that are not supporting the new HTML5 attribute, I made a fallback.
I used Modernizr to detect native support for the HTML5 placeholder attribute. Even if this could have been done by writing a short function, I love Modernizr as it also enables you to use more semantic elements from the HTML5 specs.
Chrome’s inset box-shadow bug
There is a bug on Chrome when both CSS border-radius
and inset box-shadow
properties are used. Anyway, there is good news about that. Paul Irish announced last month that Chrome’s inset box-shadow bug is fixed.
Later update
The demo was updated, thanks for pointing this out Atul.
So, if you’re using Chrome beta 10.0.648.119 or a greater version, this should work just perfect!
Conclusion
This example is mostly about progressive enhancement.
Regarding the CSS, as you will notice, this example will degrade gracefully for other old browsers. Now, regarding the HTML5 placeholder
attribute, if native support is missing, then the Javascript code will do it for you.