HTML 5 Fancy Forms

October 28th, 2012

Fancy forms like the one shown below are quite easy to make.  All it takes is a little CSS and a touch of javascript, you too can create form like the one shown below.

Fancy Form with Icons

Create the HTML Form

Create the plain old HTML form with a little HTML5 magic via the placeholder attribute.  The code below creates the form above.

<form method="post">
     <input id="visitorname" type="text" name="visitorname" placeholder="Your Name" />
     <input id="email" type="text" name="email" placeholder="Email Address" />
     <textarea id="comment" name="comment" placeholder="Comment/Message"></textarea>   
     <input type="submit" name="action" value="Submit" />
</form>

Write the CSS

First you need some small icons/images that you will use for your fancy form.  In the example form I have three images: contact.gif, email.gif, and comment.gif.  Once you have this icons ready we can start writing the CSS.   We will use the icons as the background image of input and textarea tags, telling the web browser not to tile the image.  Then we just have to indent the text enough so that it does not overlap the background image.

#visitorname{
     background-image: url(images/contact.gif);
     background-repeat: no-repeat;
     text-indent: 20px;
     border: 2px solid #DDD;
}
#email{
     background-image: url(images/email.gif);
     background-repeat: no-repeat;
     text-indent: 20px;
     border: 2px solid #DDD;
}
#comment{
     background-image: url(images/comment.gif);
     background-repeat: no-repeat;
     text-indent: 20px;
     line-height: 20px;
     border: 2px solid #DDD;
}

Make it act right with JavaScript

At this point our form should be working in most web browser except for everyone’s friend IE, specially versions less than 10.  So in order to make it work for the IE users in the world we will need to download this script from github.  and include it on our site in a script tag and include a line of code to initialize the script.

<script type="text/javascript" src="js/Placeholders.js"></script>
<script type="text/javascript">
     Placeholders.init();
</script>

Conclusion

Now you should have a fully functional HTML form that looks a bit more modern than the default.  It is great for short forms where you need to save the space that having external labels require.